繁体   English   中英

使用实体框架更新对象的所有字段

[英]Update all fields of an object using entity framework

我想使用实体框架更改所有对象属性。
搜索后,我必须有这个:

控制器,动作:

public ActionResult Test()
{
    var user = GetCurrentUser();
    user.FirstName = "BLAH BLAH";
    new UserRepository().UpdateUser(user);
    return RedirectToAction("Index");
}

在我的UserRepository中:

public bool UpdateUser(ApplicationUser target)
{
     using (var db = new AppDatabase())
     {
        db.Entry(target).State = EntityState.Modified;
        db.SaveChanges();
        return true;
     }
}

但是当我尝试执行时出现此错误

EntityChangeTracker的多个实例不能引用一个实体对象。

那么,有什么方法可以修复还是有更好的方法?
使用实体框架6.0.0和.net 4.5

public ApplicationUser GetCurrentUser()
{
   return UserManager.FindById(User.Identity.GetUserId());
}

确保所有对象都来自同一上下文!

var userContextOne = new MyDbContext();
var user = userContextOne.Users.FirstOrDefault();

var AppDbContextTwo = new MyDbContext();

// Warning when you work with entity properties here! Be sure that all objects came from the same context!
db.Entry(target).State = EntityState.Modified;

AppDbContextTwo.SaveChanges();

第二个问题(与异常无关!):

db.Entry(target).State = EntityState.Modified;

你为什么这样做? 您没有独立场景? 您是否禁用了Changetracker? 无论如何,只需执行DetectChanges,此方法将找到您不必自己进行更改的数据。

您应该使用数据库上下文的同一实例进行查找和更新,因此UserRepository可以是:

 class UserRepository : IDisposable //using IDisposable to dispose db context
 {
      private AppDatabase _context;
      public UserRepository()
      {
           _context = new AppDatabase();
      }

      public ApplicationUser Find(string id)
      {
           return _context.Set<ApplicationUser>().Find(id);
      }

      public void Update(ApplicationUserentity entity)
      {
          _context.Entry(entity).State = EntityState.Modified;
          _context.SaveChanges();
      }

      public void Dispose()
      {
           _context.Dispose();
      }   
 }

您可以在控制器中使用它:

public ActionResult Test()
{
    using (var repository = new UserRepository())
    {
         var user = repository.Find(User.Identity.GetUserId());
         user.FirstName = "BLAH BLAH";
         repository.Update(user);
    }
    return RedirectToAction("Index");
}

我也认为使用某种依赖注入框架对您会有所帮助。 所以去吧!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM