本文介绍了实体未使用“代码优先”方法更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用于数据库操作的此类:

I have this class that I use for DB operations:

public class EntityService<TEntity> : IRepository<TEntity> where TEntity : BaseModel
{

     ApplicationDbContext _context;
     private DbSet<TEntity> _entities;

     public EntityService()
     {
         _context = new ApplicationDbContext();
     }

     public virtual void Update(TEntity entity)
     {
          if (entity == null)
               throw new ArgumentNullException(nameof(entity));

          try
          {
                var dbEnt = _context.Set<TEntity>().Where(c => c.Id == entity.Id).First();

                dbEnt = entity;
                dbEnt.UpdatedBy = GetCurrentUser();
                dbEnt.DateUpdated = DateTime.Now;
                _context.SaveChanges();
           }
           catch (DbUpdateException exception)
           {
                throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception);
           }

           //-----other methods for insert and get working fine----
}

此类中还有其他方法可用于插入获取工作正常。仅此更新方法不会更新实体,也不会引发异常。

There are also other methods in this class for insert and get are working fine. Only this update method is not updating the entity and not throwing the exception.

更新

我在这里遇到类似的问题,但在工作上却与此相反: Add()方法来添加重复的行对于代码优先实体框架中的链接模型

I am facing similar problem but opposite in functioning here: Add() method adding duplicate rows for linked models in Code-First Entity Framework

我认为这两个原因具有相同的变更跟踪。但是,其中一个正在添加,其他却没有更新。

I think these two have same reason of Change Tracking. But one is adding other is not updating.

推荐答案

该行...

var dbEnt = _context.Set<TEntity>().Where(c => c.Id == entity.Id).First();

...将实体对象附加到上下文并返回对该实体的引用。

...attaches an entity object to the context and returns a reference to this entity.

然后一行...

dbEnt = entity;

...通过引用实体进入方法的变量。那不是跟踪的对象对象。您基本上失去了对跟踪实体的引用,因此无法再对其进行更改。

...replaces this reference by a reference to the entity variable that enters the method. That is not the tracked entity object. You basically lost the reference to the tracked entity and it's impossible to change it any longer.

您应该附加实体到上下文中并将其标记为已修改,或者像以前一样获取 dbEnt 并修改并保存那个对象。两种方法都有优缺点,请参见。

You should either attach entity to the context and mark it as modified, or get dbEnt as you already do and modify and save that object. Both methods have pros and cons, see here.

这篇关于实体未使用“代码优先”方法更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:22