简体   繁体   中英

Insert Master-Detail with LINQ

I want to insert a master-detail with the following structure:

Every Sale has an Id, date and a Client, Employee and SaleDetail. Every Sales Detail has a pieces number and price and of course a reference to its master and which product is.

I tried the following code but I cannot get it to work:

private void GenerarNota()
{
    EntityCollection<SalesDetail> details = new EntityCollection<SalesDetail>();

    foreach (ListItem item in _productList)
    {
        SalesDetail detail = new SalesDetail();
        detail.Product = db.Product.FirstOrDefault(p => p.Id == item.Id);
        detail.Pieces = item.Pieces;
        detail.Price = item.Price;

        details.Add(detail);
    }

    Sale sale = new Sale
    {
        Client = (Client )txtCliente.Item,
        Employee = (Employee )txtEmp.Item,
        SalesDetail = details
    };

    db.AddToSale(sale);
    db.SaveChanges();
}

The exception I got:

The object could not be added to the EntityCollection or EntityReference. An object that is attached to an ObjectContext cannot be added to an EntityCollection or EntityReference that is not associated with a source object.

Am I doing something wrong? I read about attaching and dettaching objects but after I tried that I got a FK constraint violation.

Can you please tell me what I'm doing wrong or if it's another way to do it? I'm very new at LINQ, I could perfectly do it in pure SQL but I wanted to learn about it.

detail.Product is still associated with db. Prices and Pieces may be associated with it as well. The system is very strict in ensuring that every object can only be associated with one object context (your db) or completely detached (your EntityCollection<>).

Either your details EntityCollection needs to be associated with db (no idea how to do this) or all your objects must be properly detached before they're tacked into details.

Honestly, I'd just reorder things around - create Sale first and add it, then start inserting things into Sale.SalesDetail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM