我的超市模型包含一个 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();
}
}
}
问题是:当警报被保存时,一个新的库存项目(具有不同的 id)被添加到数据库中,尽管它已经存在了!任何解决方案?