Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...