开发者

Linq to Sql Add and Delete in same transaction

i have an action method for update of master detail record. when data first reaches from view to controller, i select the previous records from db and call delete method of repository.

public ActionResult sale(int id, SaleRecord _SaleRecord,int? PositionID)
        {
            SalesRepository _SalesRepository = new SalesRepository();
            if (ModelState.IsValid)
            {
                List<long> prevSaleIDs = _SaleRecord.Items.Where(y => y.ActualSaleID > 0).Select(x => x.ActualSaleID).Distinct().ToList();
                foreach (var SaleID in prevSaleIDs) 
                {
开发者_运维知识库                    var dbData = _SalesRepository.GetSale(SaleID);
                    _SalesRepository.DeleteSaleItems(dbData.mktActualSaleItems.ToList());
                    _SalesRepository.DeleteActualSales(dbData);
                }
-----
-----
}

after putting the records for delete i prepare new record by calling updateModel and put it for insert

public ActionResult sale(int id, SaleRecord _SaleRecord, int? PositionID)
{
   //as above 
   mktActualSale _Sales = new mktActualSale();
                UpdateModel(_Sales, "_SaleRecord");
                _Sales.mktActualSaleItems.AddRange(_SaleRecord.Items.Where(z => z.SalesQuantity != 0).Select(x => new mktActualSaleItem { SalesQuantity = x.SalesQuantity, SKUID = x.SKUID }));
                _SalesRepository.Add(_Sales);
                _SalesRepository.Save();
}

but when save is called, it gives me exception telling that unique key constraint is violated in db. the reason of this constraint being violated is previous record is not deleted from database and it simply wants to add another record on top of it. How can i solve this problem

regards


So why don't call _SalesRepository.Save(); before add new records ??

Update:

But isn't better to make Update instead of delete and add. Just get the records and update them all using try catch then if everything OK do save.

Hope this helped

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜