当我执行涉及从文件插入数据或更新(如果存在)的代码时,我遇到了一个大问题。我正在使用实体框架。文件接近 16 000 行
我试图插入它们,但我花了很多时间这样做:超过 5 小时的 x 文件。
我决定改变它,但我不知道如何开始。
我读了一些关于保存每 1000、5000、10000 行的内容,但是当我尝试这样做时遇到了异常。
Store update, insert, or delete statement affected an unexpected number of rows (0).
Entities may have been modified or deleted since entities were loaded. Refresh
ObjectStateManager entries.
当我试图修复它时,我得到了这个异常
AcceptChanges can not continue because the object's key values conflict with another
object in ObjectStateManager. Make sure that the key values are unique before calling
AcceptChanges.
这是我的代码
//before this I passed db data to lists
foreach (var record in records)
{
if (record != null)
{
try
{
if (!_location.Any(s => s.Id.Trim() == record.Id))
{
Location l = new Location
{
Id = record.Id,
Name = record.Name,
Address = record.Address,
City = record.City,
State = record.State,
Zip = record.Zip.ToString(),
Zip2 = record.Zip2,
Custom1 = record.Custom1,
CreatedDate = date,
UpdatedDate = date
};
db.location.Add(l);
db.SaveChanges();
_location.Add(l);
}
else
{
if (!_sales.Any(s => s.LocationId == record.Id && s.ReportDate == record.ReportDate))
{
Sale s = new Sale
{
ReportDate = record.ReportDate,
CreatedDate = date,
UpdatedDate = date,
Amount = record.Amount,
LocationId = record.Id,
};
db.Sale.Add(s);
db.SaveChanges();
_sales.Add(s);
}
else
{
if (!_sales.Any(s => s.LocationId == record.Id && s.ReportDate == record.ReportDate && s.Amount == record.Amount))
{
if ((_sales.Where(s => s.LocationId == record.Id && s.ReportDate == record.ReportDate)).Count() == 1)
{
var sale = _sales.SingleOrDefault(s => s.LocationId == record.Id && s.ReportDate == record.ReportDate);
sale.UpdatedDate = date;
sale.Amount = record.Amount;
db.Entry(sale).State = EntityState.Modified;
db.SaveChanges();
}
}
}
}
}
catch (Exception ex)
{
}
}
}
我所做的更改是:
在 foreach 结束时仅将所有 db.SaveChanges 更改为一个,我得到了第一个异常(也是当我将它们按 3000 分组时)
更改实体状态,我得到了第二个异常。
我会感谢你的帮助,
谢谢。