EntityFramework partial model update

asp.net-mvc c# entity-framework windows

Question

I'm working on an MVC project using the repository pattern and entity framework; right now, a sample model is shown on my form.

SampleModel
1) name
2) age
3) Identify
4) notes
5) Updated date

On the edit form, I am simply showing the data below.
1) name
2) age
3) Identify

Now, if I use the repository to update the model with missing property values, the notes, dateupdated field becomes null.

My concern is how to use the repository to update just a few chosen properties (tryupdatemodel is not included in the repository). I do not want to call the original object and map the properties to the updated model.

There must be a way, somewhere.

1
16
5/3/2013 9:30:36 AM

Accepted Answer

You may only change a portion of the fields:

using (var context = new YourDbContext())
{
    context.SamepleModels.Attach(sampleModel);

    DbEntityEntry<SameplModel> entry = context.Entry(sampleModel);
    entry.Property(e => e.Name).IsModified = true;
    entry.Property(e => e.Age).IsModified = true;
    entry.Property(e => e.Address).IsModified = true;   

    context.SaveChanges();
}

or using the ObjectContext API

using (var context = new YourObjectContext())
{
    context.SamepleModels.Attach(sampleModel);

    ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(sampleModel);
    entry.SetModifiedProperty("Name");
    entry.SetModifiedProperty("Age");
    entry.SetModifiedProperty("Address"); 

    context.SaveChanges();
}
21
3/22/2012 11:04:09 AM

Popular Answer

This post is old, but if anybody is interested, we've developed a useful extension technique for EF 4.1 and newer to build on Ladislav's solutions:

public static void SetModified<TEntity>(
        this DbEntityEntry<TEntity> entry,
        IEnumerable<Expression<Func<TEntity, object>>> expressions) where TEntity : class, IEntity
    {
        foreach (var expression in expressions)
            entry.Property(expression).IsModified = true;
    }

Unless you're using an interface with the same name for your POCOs, you'll need to remove the IEntity constraint.

Usage examples include:

        var user = new User
        {
            Id = Request.Id,
            UserName = Request.UserName,
            FirstName = Request.FirstName
        };

        var expressions = new List<Expression<Func<User, object>>> 
                 { 
                     x => x.UserName, 
                     x => x.FirstName
                 };

        context.Entry(user).SetModified(expressions);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow