2014-12-29 67 views
0

我定義一個類的項目如下:如何設置默認值在MVC模型動態

public enum ContractFreq 
{ 
    [Display(Name="Monthly")] 
    M = 1, 
    [Display(Name="Quarterly")] 
    Q = 2, 
    [Display(Name="Anually")] 
    A = 3, 
    [Display(Name="One-Time")] 
    X = 4 
} 

public partial class Project 
{ 
    [Key] 
    [Display(Name="Project")] 
    public int ProjectID { get; set; } 
    [Display(Name = "Contract Frequency")] 
    public ContractFreq ContractFreq { get; set; } 
    [Required] 
    public string Description { get; set; } 
    [ForeignKey("Vendor")] 
    public int VendorID { get; set; } 
    public int Cost { get; set; } 
    [Display(Name = "Project Start Date")] 
    public DateTime? DateStarted { get; set; } 
    [Display(Name = "Project Name")] 

    private String _ProjectName = Vendor.VendorName + " - [" + Description + "]"; 
    [Display(Name = "Project Name")] 
    public String ProjectName 
    { 
     get 
     { 
      return _ProjectName; 
     } 
     set 
     { 
      this._ProjectName = Vendor.VendorName + " - [" + this.Description + "]"; 
     } 
    } 
    /* 
    public string ProjectName 
    { 
     get 
     { 
      return Vendor.VendorName + " - [" + Description + "]"; 
     } 
    } 
    */ 


    /* Navigation */ 
    public virtual Vendor Vendor { get; set; } 
    public virtual ICollection<PurchReq> PurchReqs { get; set; } 
    public virtual ICollection<Invoice> Invoices { get; set; } 

    public Project() 
    { 
     DateStarted = System.DateTime.Now; 
     PurchReqs = new HashSet<PurchReq>(); 
    } 

,我想現場「項目名」是Vendor.VendorName和的concatentation的項目介紹。我知道字符串參數不能爲空。實現這個最簡單和最簡單的方法是什麼?我原來使用:

 public string ProjectName 
    { 
     get 
     { 
      return Vendor.VendorName + " - [" + Description + "]"; 
     } 
    } 

但我無法使用LINQ與非靜態字段,並想知道是否有更好的方法。

回答

0

它可以是這樣的:

[Display(Name = "Project Name")] 
public String ProjectName 
{ 
    get 
    { 
     return string.Format("{0} - [{1}]", Vendor.VendorName, Description); 
    } 
} 

並沒有靜態成員read this