2014-12-29 146 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