ASP.NET C# Entity Framework

Updating or Replacing Entities in Entity Framework 6

I’ve been working with Entity Framework for a few years and one pain-point for me was updating existing data entities. It typically ended up being tedious property replacement that made the code look nasty, and caused the risk of mis-matching property assignments or missing a property assignment completely. For instance:

public class MyEntityRepository
{
    public MyEntity UpdateTheOldWay(int id, MyEntity newEntityValues)
    {
        using (var context = new MyDbContext())
        {
            var entity = context.MyEntities.Find(id);
            
            entity.MyProperty = newEntityValues.MyProperty;
            entity.MyAProperty = newEntityValues.MyAProperty;
            entity.MyBProperty = newEntityValues.MyBProperty;
            entity.MyCProperty = newEntityValues.MyBProperty;
            entity.MyDProperty = newEntityValues.MyDProperty;
            entity.MyEProperty = newEntityValues.MyEProperty;

            return entity;
        }
    }
}

Spot the error? These things happen. Sometimes they get caught quick, sometimes they slip by. It also took 6 lines for this fairly small model; over time that starts to get a little nastier.

DbEntityEntry to the rescue!

I’m not sure how this alluded me for so long because it’s such a nice solution in my opinion.

public class MyEntityRepository
{
    public MyEntity Update(int id, MyEntity newEntityValues)
    {
        using (var context = new MyDbContext())
        {
            var entity = context.MyEntities.Find(id);
            context.Entry(entity).CurrentValues.SetValues(newEntityValues);
            context.SaveChanges();

            return entity;
        }
    }

    public MyEntity Update(int id, MyEntityViewModel viewModel)
    {
        using (var context = new MyDbContext())
        {
            var entity = context.MyEntities.Find(id);
            context.Entry(entity).CurrentValues.SetValues(viewModel);
            context.SaveChanges();

            return entity;
        }
    }
}

In the first method, we are replacing a MyEntity with a new MyEntity completely. Pretty cool! However in the second method, we’re using a MyEntityViewModel. This is interesting to note; the SetValues method takes in a generic object and will update all the properties that match on both the entity and the object you pass into the SetValues method. You can also use Dictionaries with property keys as the tuple key. For more information, check out this MSDN article.

Enjoy!

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *