2011-02-08 159 views
2

我對MVC和EF代碼第一次比較陌生,無法找到解決此問題的方法。.NET MVC 3/EF代碼優先 - 添加相關實體

我已經使用EF代碼首先創建2個實體,發票和InvoiceItem。一個發票可以有許多InvoiceItem實例。 InvoiceItem只能有一個Invoice實例。

代碼片段如下:

public class Invoice 
{ 
    [ScaffoldColumn(false)] 
    public int InvoiceId { get; set; } 
    public string Description { get; set; } 

    public virtual ICollection<InvoiceItem> InvoiceItems { get; set; } 
} 

public class InvoiceItem 
{ 
    [ScaffoldColumn(false)] 
    public int InvoiceItemId { get; set; } 

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:C}")] 
    public decimal Amount { get; set; } 

    public virtual Invoice Invoice { get; set; } 
} 

protected override void OnModelCreating(ModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Invoice>().HasMany(i => i.InvoiceItems); 
    modelBuilder.Entity<InvoiceItem>().HasRequired(i => i.Invoice); 
} 

作爲一個測試,我只是想爲下面的代碼的發票創建一個InvoiceItem

if (ModelState.IsValid) 
{ 
    _repository.Add(invoice); 
    _repository.Save(); 

    invoice.InvoiceItems.Add(new InvoiceItem {Amount = 99}); 

    return RedirectToAction("Index"); 
} 

當它到達invoice.InvoiceItems.Add()行,它會引發一個「未設置爲對象實例的對象引用」。錯誤。

我錯過了什麼?

回答

3

我最初這裏的猜測是「InvoiceItems」屬性尚未初始化。你可以做一個空檢查您添加到集合之前:

private ICollection<InvoiceItem> invoiceItems; 

public ICollection<InvoiceItem> InvoiceItems 
{ 
    get 
    { 
     return this.invoiceItems ?? (this.invoiceItems = new List<InvoiceItem>()); 
    } 
} 
+0

我知道:

if(invoice.InvoiceItems == null) { invoice.InvoiceItems = new List<InvoiceItem>(); } invoice.InvoiceItems.Add(new InvoiceItem {Amount = 99}); 

通過在get {}如果它是空創建一個私有字段和initalise或者使InvoiceItems只讀屬性這是顯而易見的,我失蹤了。謝謝@santos第二個解決方案的工作就像一個魅力 - 除了我必須使公共財產虛擬。 – 2011-02-08 22:05:19