我的超市模型包含一个 StockItem 类和一个包含 StockItem 字段的 Alert 类:
public class StockItem
{
public int ID { get; set; }
public string Name { get; set; }
public int CurrentQuantity { get; set; }
public int MinQuantity { get; set; }
}
public class Alert
{
public int ID { get; set; }
public int Message{ get; set; }
public virtual StockItem StockItem { get; set; }
}
我有一个使用一个 DbContext 获取所有 StockItems 的函数:
using (var db = new MyDbContext())
{
return db.StockItems.ToList();
}
另一个处理这些项目的函数,并在另一个 DbContext 中添加新的警报:
foreach (var item in items)
{
if (item.CurrentQuantity < item.MinQuantity)
{
using (var db = new MyDbContext())
{
db.Alerts.Add(new Alert(){StockItem = item, Message = "Low Quantity"});
db.SaveChanges();
}
}
}
问题是:当一个警报被保存时,一个新的 Stock Item(具有不同的 id)被添加到数据库中,尽管它已经存在了!
任何解决方案?
最佳答案
我觉得你应该Attach
首先是库存项目。
尝试这个:
foreach (var item in items)
{
if (item.CurrentQuantity < item.MinQuantity)
{
using (var db = new MyDbContext())
{
db.StockItems.Attach(item);
db.Alerts.Add(new Alert {StockItem = item, Message = "Low Quantity"});
db.SaveChanges();
}
}
}
关于entity-framework - Entity Framework SaveChanges() 在不同的 DbContext 中插入不必要的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6107204/