How to update not every fields of an object using Entity Framework and EntityState.Modified

前端 未结 5 1328
鱼传尺愫
鱼传尺愫 2020-12-02 10:49

I need to update all fields except property1 and property2 for the given entity object.
Having this code:

    [HttpPost]
    public ActionResult Add(ob         


        
5条回答
  •  再見小時候
    2020-12-02 11:22

    This question was already nicely answered, but I wanted to provide an extension method for anyone who would like to use it.

    This code was developed for EF 4.3.1

    //You will need to import/use these namespaces    
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;    
    
    //Update an entity object's specified columns, comma separated
    //This method assumes you already have a context open/initialized
    public static void Update(this DbContext context, T entityObject, params string[] properties) where T : class
    {
        context.Set().Attach(entityObject);
    
        var entry = context.Entry(entityObject);
    
        foreach(string name in properties)
            entry.Property(name).IsModified = true;
    
        context.SaveChanges();
    }
    

    Usage Example

    using (FooEntities context = new FooEntities())
    {
        FooEntity ef = new FooEntity();
    
        //For argument's sake say this entity has 4 columns: 
        //    FooID (PK), BarID (FK), Name, Age, CreatedBy, CreatedOn
    
        //Mock changes
        ef.FooID = 1;
        ef.Name = "Billy";
        ef.Age = 85;
    
        context.Update(ef, "Name", "Age"); //I only want to update Name and Age
    }
    

提交回复
热议问题