【发布时间】:2019-10-11 15:28:44
【问题描述】:
我有这个类用于数据库操作:
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----
}
这个类中还有其他用于insert 和get 的方法工作正常。只有这个更新方法不会更新实体并且不会抛出异常。
更新
我遇到了类似的问题,但在这里的功能相反:Add() method adding duplicate rows for linked models in Code-First Entity Framework
我认为这两者有相同的更改跟踪原因。但是一个是添加另一个不是更新。
【问题讨论】:
-
如果你想更新
entity为什么你又得到它并将entity放入dbEnt? -
@hassan.ef 当我这样做时它不起作用。所以我想如果我再次从数据库中获取数据库实体,那么 _context 将有它的数据库引用。因为
entity只是方法参数。 -
我认为首先你应该像这样用
entity的参数更新dbEnt的参数:例如:edbEnt.Name = entity.Name并且不要使用dbEnt = entity。 -
@hassan.ef 这是更新所有实体的常用方法。我不能在这里明确地分配单个属性。
-
保存前,您可以尝试拨打
context.Entry(entity).State=EntityState.Modified;。
标签: c# .net asp.net-mvc entity-framework ef-code-first