Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework update partial model

I am working on mvc project, with repository pattern and entity framework, now on my form i have a sample model

SampleModel
1) name
2) age
3) address
4) notes
5) date updated

I am displaying only following data on the edit form
1) name
2) age
3) address

now if i update the model with missing property values using the repository, the notes, dateupdated field goes null.

My question is how do i update only few selected properties using the repository ( tryupdatemodel not available in repository ) and i dont want to call the original object and map the properites with the updated model.

Is there any way, there must be.

like image 784
Milan Avatar asked Mar 22 '12 10:03

Milan


1 Answers

You can update only subset of 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 in 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();
}
like image 58
Ladislav Mrnka Avatar answered Sep 21 '22 12:09

Ladislav Mrnka