db.SaveChanges()爆炸与事务异常

时间:2012-11-25 19:56:41

标签: c# asp.net sql linq

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

感谢。

1 个答案:

答案 0 :(得分:0)

不确定为什么会发生这种情况,但如果您还检查了SaveChanges() Local的{​​{1}}集合,则不需要第一个db.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