How to add existing collection of entities to existing entity without pulling first pulling existing entities from database using code-first framework

。_饼干妹妹 提交于 2019-12-24 10:39:44

问题


I'm trying to attach two existing and one new bid bid to an existing auction, but am unable to do so without first pulling the product from the database.

This code works, but how would I go about just providing the bid id's for the existing bids and then save the auction

using (var db = new DataContext())
    //find existing auction
    var auction = db.Auctions.Find(1);

    var bid1 = db.Bids.Find(1);
    var bid2 = db.Bids.Find(2);
    var bid3 = new Bid()
    {
        //New Bid
    };

    //existing
    auction.Bids.Add(bid1);
    //existing
    auction.Bids.Add(bid2);
    //new
    auction.Bids.Add(bid3);
    db.SaveChanges();
}

EDIT - I tried this as well, but got a referential integrity problem: with the following innerexception:

{"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."}

        using (var db = new DataContextContext())
        {
            var auction = db.Auctions.Find(1);
            var bid1 = new Bid() { BidId = 1 };
            db.Bids.Attach(bid1);
            auction.Bids.Add(bid1);
            db.SaveChanges();
        }

回答1:


You can use Attach to add known entities to the db context.

using (var db = new DataContext()) {
    //find existing auction
    var auction = db.Auctions.Find(1);
    var bid1 = new Bid() { BidId = 1 };
    var bid2 = new Bid() { BidId = 2 };

    var bid3 = new Bid()
    {
        //New Bid
    };

    //existing
    db.Attach(bid1);
    auction.Bids.Add(bid1);
    //existing
    db.Attach(bid2);
    auction.Bids.Add(bid2);
    //new
    auction.Bids.Add(bid3);
    db.SaveChanges();
}


来源:https://stackoverflow.com/questions/7287414/how-to-add-existing-collection-of-entities-to-existing-entity-without-pulling-fi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!