BendEg
BendEg

Reputation: 21088

Updating EF model in new DbContext instance

What is the best way to update an entity framework model in the database with two instances of a DbContext. For example i have a simple User model which is loaded in one DbContext but saved in another:

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();
}

In my case i want to write some UserManager, which has Create, Update and Delete methods. I think creating one DbContext instance for the howle manager is no solution, because i only want to save the changes of a specific model.

I also don't want to load the models for updating again from the database and settings each value from the source instance, like:

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

Maybe my problem with manager classes is very simple, but i could not find any good solution.

P.S.: My manager classes are often singleton classes.

Thank you.

Upvotes: 0

Views: 603

Answers (1)

Marc Harry
Marc Harry

Reputation: 2430

You could in your second DbContext do something like this:

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

This would save the changes you have made to the entity to the database. However I can't remember if dbContext.Entry queries the DB for the entity.

Upvotes: 2

Related Questions