Diana
Diana

Reputation: 287

EntityFramework in .NET - when adding child entity to existing parent, parent is being validated/added

I am using EntityFramework with .NET and I have, among others, entities Invoice (parent) and receipt (child). They are modeled as shown below:

public class Invoice
{       
  public int InvoiceID { get; set; }

  [Required(ErrorMessage = "Field Date is mandatory for the invoice.")]
  public DateTime Date { get; set; }
  ...
  public virtual ICollection<Receipt> Receipts { get; set; }
}

public class Receipt
{     
  public int ReceiptID { get; set; }
...
  public int? InvoiceID { get; set; }    
  public Invoice Invoice { get; set; }
}

I have the invoice added in the database already. The problem is when I try to add a receipt for it. In order to do this, I use a FormView, with properties ItemType="Models.Receipt", ValidateRequestMode="Enabled", InsertMethod="AddReceipt":

public void AddReceipt(Models.Receipt receiptObj)
{
  receiptObj.InvoiceID = intInvoiceID; //from POST
  if (ModelState.IsValid)
    {
       var _db = new Models.InvoiceContext();
       _db.Receipts.Add(receiptObj);
       _db.Entry(receiptObj).State = System.Data.Entity.EntityState.Added;
      _db.SaveChanges();            
    }
 }

The ModelState.IsValid returns false. The error message is "Field Date is mandatory for the invoice." - But I am not trying to add an invoice! When I inspect the "ModelState" in Debug, in ModelState.Keys I see values "Invoice.InvoiceNumber" and "Invoice.InvoiceDate"...?

If I try to load the invoice

receiptObj.Invoice= GetInvoice(intInvoiceID);

I still get the same validation error, even if when I inspect in Debug the invoice.Bill, I see that it is loaded properly- including the date field. (But fetching the invoice this way is not ok because I'll receive another error when I solve the validation problem because I use a different context when I call GetInvoice(intInvoiceID) and I can't attach the invoice object to two different contexts.)

I'm stuck with this for some time, so any help is greatly appreciated.

Upvotes: 2

Views: 453

Answers (1)

Diana
Diana

Reputation: 287

I found the problem! I'm posting it in case someone else encounters it.

Inside the FormView which I use to insert/upate the receipt, I had a label which displayed the invoice number.

<asp:Label ID="lblInvoiceNumber_edit" Text='<%# Bind("Invoice.InvoiceNumber") %>' runat="server"></asp:Label>

Because of the Bind, each time I was trying to insert/update a receipt, the context was also trying to insert a new invoice - but since for this new invoice only the InvoiceNumber field was bound, all the other fields were null - this is why the validation for the mandatory field Date of the invoice failed.

Thank you all for your interest and suggestions.

Upvotes: 1

Related Questions