1

我有一个空的数据库。我想将多条记录添加到数据库中。在将记录插入数据库时​​,我想检查我在同一日期插入的产品是否再次添加(我想更改它的一些归档并更新它的内容)。我使用了这段代码,但它只是将一些数据添加到数据库中(它无法检查现有产品。)

var AllData = ClsDataBase.Database.InsertProductTbls;

 foreach(item in AllData)
        {
          //Update  
          if (Exist(datefa))
            {
            var query = ClsDataBase.Database.CustomerProductTbls.SingleOrDefault
                    (data => data.CustomerId == AllData .CustomerId );

                    int? LastProductTotal = query.CustomerProducTtotal;
                    query.CustomerProducTtotal = LastProductTotal + ClsInsertProduct._InsertProductNumber;

                }
                //Insert 
                else
                {
                    _CustomerProductTbl = new CustomerProductTbl();
                    _CustomerProductTbl.CustomerId = AllData ._CustomerId;
                    _CustomerProductTbl.CustomerProductDateFa = AllData.datefa
                    .
                    .
                    .
                    ClsDataBase.Database.AddToCustomerProductTbls(_CustomerProductTbl);
                }
            }
        }
        ClsDataBase.Database.SaveChanges();

如果我ClsDataBase.Database.SaveChanges();同时用于更新和插入部分,我将返回此错误:

An error occurred while starting a transaction on the provider connection. See the inner exception for details.

请帮忙。

4

1 回答 1

0

我通过为每个重复循环打开数据库连接得到了解决方案:

foreach(item in AllData)
        {
           using (StorageEntities context = new StorageEntities())
           {
         //Update  
          if (Exist(datefa))
            {
            var query = ClsDataBase.Database.CustomerProductTbls.SingleOrDefault
                    (data => data.CustomerId == AllData .CustomerId );

                    int? LastProductTotal = query.CustomerProducTtotal;
                    query.CustomerProducTtotal = LastProductTotal + ClsInsertProduct._InsertProductNumber;

                }
                //Insert 
                else
                {
                    _CustomerProductTbl = new CustomerProductTbl();
                    _CustomerProductTbl.CustomerId = AllData ._CustomerId;
                    _CustomerProductTbl.CustomerProductDateFa = AllData.datefa;
                    ClsDataBase.Database.AddToCustomerProductTbls(_CustomerProductTbl);
                }
                ClsDataBase.Database.SaveChanges();
            }
         }
于 2012-08-07T08:38:45.463 回答