I’m relatively new to MVC and EF Code first and cannot find a solution to this problem.
I have used EF code first to create 2 entities, Invoice and InvoiceItem. One Invoice can have many instances of InvoiceItem. InvoiceItem can only have one instance of Invoice.
Code snippets as follows:
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);
}
As a test, I’m just trying to create one InvoiceItem for an Invoice with the following code
if (ModelState.IsValid)
{
_repository.Add(invoice);
_repository.Save();
invoice.InvoiceItems.Add(new InvoiceItem {Amount = 99});
return RedirectToAction("Index");
}
When it gets to the invoice.InvoiceItems.Add() line, it throws an “Object reference not set to an instance of an object.” error.
What am I missing?
My initial guess here is that the ‘InvoiceItems’ property hasn’t been initialised. You could do a null check before you add to the collection:
Alternatively make InvoiceItems a readonly property by creating a private field and initalise in the get {} if it’s null: