在新的 DbContext 实例中更新 EF 模型

Updating EF model in new DbContext instance

使用 DbContext 的两个实例更新数据库中 entity framework 模型的最佳方法是什么。例如,我有一个简单的 User 模型,它在一个 DbContext 中加载但在另一个中保存:

User model = null;

using(SampleDbContext dbContext = new SampleDbContext())
{
    model = dbContext.User.Find(0);
}

model.UserName = "Test-User";

using(SampleDbContext dbContext = new SampleDbContext())
{
    // Here is the place i want to save the changes of the model
    // without loading it again from the database and set each property

    // ...
    dbCotnext.SaveChanges();
}

在我的例子中,我想写一些 UserManager,它有创建、更新和删除方法。我想为 howle manager 创建一个 DbContext 实例 没有解决办法,因为我只想保存特定型号的更改。

我也不想加载模型以从数据库中再次更新并设置源实例中的每个值,例如:

// Update user
using(SampleDbContext dbContext = new SampleDbContext())
{
    // I don't want this:
    var model = dbContect.User.Find(0);
    model.UserName = sourceModel.UserName;
    // ...
   dbCotnext.SaveChanges();
}

也许我和经理类的问题很简单,但我找不到好的解决办法。

P.S.: 我的经理类经常单身类.

谢谢。

您可以在第二个 DbContext 中执行如下操作:

using (SampleDbContext dbContext = new SampleDbContext())
{
    dbContext.Entry(model).State = EntityState.Modified;
    dbContext.SaveChanges();
}

这会将您对实体所做的更改保存到数据库中。但是我不记得 dbContext.Entry 是否在数据库中查询实体。