EntityFramework update partial model

前端 未结 2 1152
无人共我
无人共我 2020-12-13 15:46

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

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 16:13

    You can update only subset of fields:

    using (var context = new YourDbContext())
    {
        context.SamepleModels.Attach(sampleModel);
    
        DbEntityEntry 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();
    }
    

提交回复
热议问题