以下方法导致 FIRSTdb.SaveChanges()
抛出异常:(不允许新事务,因为会话中还有其他线程在运行。)
protected void btnInsertDependencies_Click(object sender, EventArgs e)
{
using (icmsEntities db = new icmsEntities())
{
var divisions = db.Divisions;
foreach (var division in divisions)
{
var dlc_sectors = db.Sectors.Where(s => s.Website.division_id == division.division_id).DistinctBy(s => s.name).ToList();
foreach (var sector in dlc_sectors)
{
dlc_Sector dlc_sector = new dlc_Sector
{
name = sector.name,
division_id = sector.Website.division_id
};
db.dlc_Sectors.AddObject(dlc_sector);
var dlc_products = db.Products.Where(p => p.Sectors
.Any(s => s.Website.division_id == dlc_sector.division_id && s.name == dlc_sector.name))
.DistinctBy(p => p.name).ToList();
foreach (var product in dlc_products.ToList())
{
var dlc_product = db.dlc_Products.SingleOrDefault(p => p.name == product.name);
if (dlc_product == null)
{
dlc_product = new dlc_Product { name = product.name };
db.dlc_Products.AddObject(dlc_product);
}
dlc_product.dlc_Sectors.Add(dlc_sector);
db.SaveChanges();
}
}
}
db.SaveChanges();
}
}
首先db.SaveChanges()
是确保不会再次插入具有相同名称的新产品。
我该如何解决这个问题?提前致谢。
为我工作:
var Local = db.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added)
.Where(es => es.Entity is dlc_Product).Select(es => es.Entity as dlc_Product);
var dlc_product = db.dlc_Products.SingleOrDefault(p => p.name == product.name)
?? Local.SingleOrDefault(p => p.name == product.name);
谢谢。