用Entity FrameWrok进行开发时, insert的时候,发现有时候entityframework会同时插入两条数据
两条数据插入的时间相差约一秒,但在前端请求只请求了一次,且在插入方法调用之前有做数据是否有数据存在的判断;出现该问题不知道如何处理,特上来请教园子里的大神们
先行谢谢
以下是我的代码
using (Model.EFModel.Entities entity = new Model.EFModel.Entities())
{
string ino = txt_ShipInvoice_InvoiceNo.Text.Trim();
var ckinvoice = (from s in entity.Tbl_ShipInvoice
where s.ShipInvoice_InvoiceNo == ino && s.Tbl_Shipment.Shipment_NO != lbl_shipNO.Text
select s).ToArray();
if (ckinvoice.Count()>0)
{
lblMsg.Visible = true;
lblMsg.Text = "发票号: "+ ino +" 已经被使用";
return;
}
var ship = (from s in entity.Tbl_Shipment
where s.Shipment_id == sid
select s).SingleOrDefault();
if (ship != null)
{
Model.EFModel.Tbl_ShipInvoice invoice = new Model.EFModel.Tbl_ShipInvoice();
invoice.Shipment_id = ship.Shipment_id;
invoice.Creater_id= (int)Session["userId"];
invoice.Createtime = DateTime.Now;
invoice.ShipInvoice_InvoiceNo = txt_ShipInvoice_InvoiceNo.Text.Trim();
invoice.ShipInvoice_payFig = false;
invoice.ShipInvoice_pic = Convert.ToDecimal(txt_price.Value);
invoice.ShipInvoice_qty = InvQTY;
invoice.ShipInvoice_Invoicer = txt_ShipInvoice_Invoicer.Text.Trim();
invoice.ShipInvoice_InvoiceTime = Convert.ToDateTime(txt_ShipInvoice_InvoiceTime.Value);
invoice.ShipInvoice_totalprice = Common.PublicMethod.ConvtDecimal((InvQTY * (decimal)invoice.ShipInvoice_pic), 2);
invoice.ShipInvoice_Remarks = txt_Remarks.Text.Trim();
entity.Tbl_ShipInvoice.AddObject(invoice);
if (entity.SaveChanges()>0)
{
if (ship.Shipment_yijikaipiaoQty==null)
{
ship.Shipment_yijikaipiaoQty = 0;
}
if (ship.Shipment_yijikaipiaoTotalpic==null)
{
ship.Shipment_yijikaipiaoTotalpic = 0;
}
ship.Shipment_yijikaipiaoQty += invoice.ShipInvoice_qty;
ship.Shipment_yijikaipiaoTotalpic += invoice.ShipInvoice_totalprice;
if (entity.SaveChanges() > 0) {
txt_ShipInvoice_InvoiceNo.Text = "";
txt_ShipInvoice_InvoiceNo.Focus();
txt_InvQTY.Value = "";
Common.MessageBox.ReturnToOtherWeb(this, "开票成功,点击是转到管理页面点击否继续开票" , "ManageShipInvoice.aspx");
}
}
}
}
如下图
这样问题也不时经常有,偶尔会出现那么一两次
是不是你逻辑问题,用过ef到ef core从没遇见请求一次插入数据两次的问题,应该是你哪个地方逻辑出了问题
这个是并发的问题,在前端处理不要重复提交吧
代码太乱,实在是无法看,而且对你的业务逻辑也不熟悉。
还是从 前端检查你自己的请求开始跟踪代码看看吧
1.检查前端的请求处理了几次
2.把你的请求改成同步看有没有同样情况
还是页面刷新的问题,其实细心一点这个问题就解决了