1

以下方法导致 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);

谢谢。

4

1 回答 1

0

不知道为什么会发生这种情况,但是如果您还检查了以下集合,SaveChanges()则不需要第一个:Localdb.dlc_Products

foreach (var product in dlc_products.ToList())
{
   var dlc_product = db.dlc_Products.SingleOrDefault(p => p.name == product.name)
       ?? db.dlc_Products.Local.SingleOrDefault(p => p.name == product.name);
    ...
}

新对象被添加到Local集合中。

请注意,这db.dlc_Products.Join(db.dlc_Products.Local)看起来更高效,但它不会编译,并且相反它会db.dlc_Products为每个调用查询整体。

于 2012-11-25T20:35:16.077 回答