问题
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