entity-framework - Entity Framework SaveChanges() 在不同的 DbContext 中插入不必要的行

标签 entity-framework entity savechanges

我的超市模型包含一个 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/

相关文章:

java - @Entity 和 @Embeddable 有什么区别

php - 通过 id 查找元素并将其内容替换为 php

Eclipse Scout 在离开页面时进行检查

c# - 什么时候在 Code First Entity Framework 中创建数据库?

c# - 管理 EntityConnection 生命周期

node.js - 如何在模块中构建nodejs应用程序?

entity - 领域驱动设计 - 值对象或实体

c# - 参数值 '163753323027.987000000' 超出范围

asp.net-mvc - 将 updatemodel 与 EF4.3.1 一起使用时出现 InvalidOperationException

c# - System.Data.Spatial 或 System.Data.Entity.Spatial