【问题标题】:Remove entity: Attaching an entity of type 'X' failed because another entity of the same type already has the same primary key value删除实体:附加类型为“X”的实体失败,因为同一类型的另一个实体已经具有相同的主键值
【发布时间】:2018-10-11 11:44:06
【问题描述】:

我正在尝试使用 Repository/Service 实现设计模式 Unit Of Work。

我有:

工作单位

购物清单控制器

购物清单服务

IShoppinglistRepository(继承自 IRepository)

ShoppinglistRepostiry(继承自 Repository)

现在我正在尝试删除产品列表。

购物清单控制器:

_service.RemoveRange(products);

_service.Remove(shoppinglistInDb);

_service.Complete();

购物清单服务:

public void Remove(Shoppinglist shoppinglist)
{
    _unitOfWork.Shoppinglists.Attach(shoppinglist);
    _unitOfWork.Shoppinglists.Remove(shoppinglist);
}
public void RemoveRange(IEnumerable<Product> products)
{
    _unitOfWork.Products.AttachRange(products);
    _unitOfWork.Products.RemoveRange(products);
}
public void Complete()
{
    _unitOfWork.Complete();
}

存储库:

public void Remove(TEntity entity)
{
    _context.Set<TEntity>().Remove(entity);
}
public void RemoveRange(IEnumerable<TEntity> entities)
{
    _context.Set<TEntity>().RemoveRange(entities);
}
public void AttachRange(IEnumerable<TEntity> entities)
{
    foreach (var entity in entities)
    {
        _context.Set<TEntity>().Attach(entity);
    }
}

工作单位

public int Complete()
{
    return _context.SaveChanges();
}

当我运行它时,我收到以下错误消息:

System.InvalidOperationException: '附加'MyApp.Models.Product' 类型的实体失败,因为另一个相同类型的实体 已经具有相同的主键值。使用时可能会发生这种情况 “附加”方法或将实体的状态设置为“未更改”或 如果图中的任何实体具有冲突的键值,则“已修改”。 这可能是因为有些实体是新的,尚未收到 数据库生成的键值。在这种情况下,使用“添加”方法或 'Added' 实体状态来跟踪图形,然后设置状态 将非新实体改为“未更改”或“已修改”。

我错过了什么?

【问题讨论】:

    标签: c# asp.net-mvc unit-of-work


    【解决方案1】:

    显然我不得不将我的产品列表设置为空。

    _service.RemoveRange(products);
    
    shoppinglistInDb.Products = null;
    
    _service.Remove(shoppinglistInDb);
    
    _service.Complete();
    

    现在可以了。

    【讨论】:

      猜你喜欢
      • 2017-05-13
      • 2015-01-08
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 2017-09-25
      相关资源
      最近更新 更多