UnitOfWork 更新实体出错解决办法

本文介绍了解决Entity Framework中更新实体时遇到的主要问题之一:键冲突。当尝试使用Attach方法更新实体时,如果同一类型的另一个实体具有相同的主键值,则会出现此问题。文章提供了一个实用的方法来避免这一问题,即通过使用AsNoTracking方法来停止对实体的跟踪。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用UnitOfWork进行实体更新的时候,再查询实体一次,再去更新的时候会报如下错误:

Attaching an entity of type 'TinyFrame.Data.DomainModel.t_user_application' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

 

解决办法如下:

    public virtual async Task<T> GetOne(Expression<Func<T,bool>> where) {
            return await _dbSet.Where(where).AsNoTracking().FirstOrDefaultAsync();
        }

用AsNoTracking不进行跟踪,就可以更新了

记录下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值