25

Currently I am doing like this:

For Example:

public update(Person model)
{
    // Here model is model return from form on post
    var oldobj = db.Person.where(x=>x.ID = model.ID).SingleOrDefault();
    db.Entry(oldobj).CurrentValues.SetValues(model);
}

It works, but for example,

I have 50 columns in my table but I displayed only 25 fields in my form (I need to partially update my table, with remaining 25 column retain same old value)

I know it can be achieve by "mapping columns one by one" or by creating "hidden fields for those remaining 25 columns".

Just wondering is there any elegant way to do this with less effort and optimal performance?

5
  • Create View Model.. only add the fields you want.. Set values
    – JamieD77
    Oct 14, 2015 at 23:59
  • Even I create View Model; the same problem still exist while updating to to my table "Person". Please correct me if I am missing something Oct 15, 2015 at 0:06
  • does your viewmodel have only the 25 fields that you're displaying?
    – JamieD77
    Oct 15, 2015 at 0:18
  • Currently I have overall Person Viewmodel and I am mapping it with Omu.ValueInjector with mapper.map class. If I create a viewmodel with 25 column, how should I map with the db model and will other 25 column retain the same old value on update?? Oct 15, 2015 at 0:35
  • you got the original value from DB. just set differing values, and of course only These will be updated (identity tracking is done using PK and concurrency Tokens in EF) Oct 16, 2015 at 8:27

8 Answers 8

20

This is a very good question. By default I have found that as long as change tracking is enabled (it is by default unless you turn it off), Entity Framework will do a good job of applying to the database only what you ask it to change.

So if you only change 1 field against the object and then call SaveChanges(), EF will only update that 1 field when you call SaveChanges().

The problem here is that when you map a view model into an entity object, all of the values get overwritten. Here is my way of handling this:

In this example, you have a single entity called Person:

Person
======
Id - int
FirstName - varchar
Surname - varchar
Dob - smalldatetime

Now let's say we want to create a view model which will only update Dob, and leave all other fields exactly how they are, here is how I do that.

First, create a view model:

public class PersonDobVm
{
    public int Id { get; set; }
    public DateTime Dob { get; set; }

    public void MapToModel(Person p)
    {
        p.Dob = Dob;
    }
}

Now write the code roughly as follows (you'll have to alter it to match your context name etc):

DataContext db = new DataContext();
Person p = db.People.FirstOrDefault();

// you would have this posted in, but we are creating it here just for illustration
var vm = new PersonDobVm
{
    Id = p.Id, // the Id you want to update
    Dob = new DateTime(2015, 1, 1)  // the new DOB for that row
};

vm.MapToModel(p);
db.SaveChanges();

The MapToModel method could be even more complicated and do all kinds of additional checks before assigning the view model fields to the entity object.

Anyway, the result when SaveChanges is called is the following SQL:

exec sp_executesql N'UPDATE [dbo].[Person]
SET [Dob] = @0
WHERE ([Id] = @1)
',N'@0 datetime2(7),@1 int',@0='2015-01-01 00:00:00',@1=1

So you can clearly see, Entity Framework has not attempted to update any other fields - just the Dob field.

I know in your example you want to avoid coding each assignment by hand, but I think this is the best way. You tuck it all away in your VM so it does not litter your main code, and this way you can cater for specific needs (i.e. composite types in there, data validation, etc). The other option is to use an AutoMapper, but I do not think they are safe. If you use an AutoMapper and spelt "Dob" as "Doob" in your VM, it would not map "Doob" to "Dob", nor would it tell you about it! It would fail silently, the user would think everything was ok, but the change would not be saved.

Whereas if you spelt "Dob" as "Doob" in your VM, the compiler will alert you that the MapToModel() is referencing "Dob" but you only have a property in your VM called "Doob".

I hope this helps you.

1
  • 1
    Thanks for your suggestion, but one to one mapping is quite hectic when you got very large number of coulmns. Oct 18, 2015 at 22:09
4

I swear by EntityFramework.Extended. Nuget Link

It lets you write:

db.Person
  .Where(x => x.ID == model.ID)
  .Update(p => new Person() 
  {
    Name = newName,
    EditCount = p.EditCount+1
  });

Which is very clearly translated into SQL.

3
  • I think .Update is not available in Entity Framework Feb 17, 2016 at 0:01
  • It's nifty, but I've found it doesn't really help when using EF in conjunction with Web API 2, because the .Update() method has to instantiate the type (otherwise you get a MemberInitException). If I want to do that, I need a means of looping through the properties on my inbound object to instantiate the new one required by said method :(
    – LeeCambl
    Apr 19, 2017 at 22:24
  • @LeeCambl I don't follow. I didn't think Update actually instantiated the object. It takes an Expression<Func<...>> which is analyzed as an AST and turned into SQL.
    – Andy V
    Jul 7, 2017 at 14:29
4

Please try this way

public update(Person model)
{
    // Here model is model return from form on post
    var oldobj = db.Person.where(x=>x.ID = model.ID).SingleOrDefault();

    // Newly Inserted Code
    var UpdatedObj = (Person) Entity.CheckUpdateObject(oldobj, model);

    db.Entry(oldobj).CurrentValues.SetValues(UpdatedObj);
}

public static object CheckUpdateObject(object originalObj, object updateObj)
{
   foreach (var property in updateObj.GetType().GetProperties())
   {
      if (property.GetValue(updateObj, null) == null)
      {
         property.SetValue(updateObj,originalObj.GetType().GetProperty(property.Name)
         .GetValue(originalObj, null));
      }
   }
   return updateObj;
}
1
  • This is the right solution Aug 17, 2022 at 8:44
2

I have solved my Issue by using FormCollection to list out used element in form, and only change those columns in database.

I have provided my code sample below; Great if it can help someone else

// Here 
// collection = FormCollection from Post
// model = View Model for Person

var result = db.Person.Where(x => x.ID == model.ID).SingleOrDefault();
if (result != null)
{
    List<string> formcollist = new List<string>();
    foreach (var key in collection.ToArray<string>())
    {
        // Here apply your filter code to remove system properties if any
        formcollist.Add(key);
    }
    foreach (var prop in result.GetType().GetProperties())
    {
            if( formcollist.Contains(prop.Name))
            {
                    prop.SetValue(result, model.GetType().GetProperty(prop.Name).GetValue(model, null)); 
            }
    }
    db.SaveChanges();
}
1
  • 3
    Whilst this may work and saves you some coding, here is a question for you to think about - how well will this code work when someone changes a property name in your view model? Imagine someone changes "Dob" to "DateOfBirth" during a refactor. How will your code work then? You have no compiler safety at all. What will happen is that the user will enter a value into "DateOfBirth", but it will not get applied to the Dob field. The user says they entered a Dob, but your DB will say they haven't. Oct 19, 2015 at 10:59
1

I still didn't find a nice solution for my problem, so I created a work around. When loading the Entity, I directly make a copy of it and name it entityInit. When saving the Entity, I compare the both to see, what really was changed. All the unchanged Properties, I set to unchanged and fill them with the Database-Values. This was necessary for my Entities without Tracking:

        // load entity without tracking
        var entityWithoutTracking = Context.Person.AsNoTracking().FirstOrDefault(x => x.ID == _entity.ID); 
        var entityInit = CopyEntity(entityWithoutTracking);

        // do business logic and change entity
        entityWithoutTracking.surname = newValue;

        // for saving, find entity in context
        var entity = Context.Person.FirstOrDefault(x => x.ID == _entity.ID);
        var entry = Context.Entry(entity);
        entry.CurrentValues.SetValues(entityWithoutTracking);
        entry.State = EntityState.Modified;

        // get List of all changed properties (in my case these are all existing properties, including those which shouldn't have changed)
        var changedPropertiesList = entry.CurrentValues.PropertyNames.Where(x => entry.Property(x).IsModified).ToList();
        foreach (var checkProperty in changedPropertiesList)
        {
            try
            {
                var p1 = entityWithoutTracking.GetType().GetProperty(checkProperty).GetValue(entityWithoutTracking);
                var p2 = entityInit.GetType().GetProperty(checkProperty).GetValue(entityInit);
                if ((p1 == null && p2 == null) || p1.Equals(p2))
                {
                    entry.Property(checkProperty).CurrentValue = entry.Property(checkProperty).OriginalValue; // restore DB-Value
                    entry.Property(checkProperty).IsModified = false; // throws Exception for Primary Keys
                }
            } catch(Exception) { }
        }
        Context.SaveChanges(); // only surname will be updated
2
  • Why not use tracking and rely on Automatic Detect changes as described in learn.microsoft.com/en-us/ef/core/change-tracking/… ? Jan 29 at 11:47
  • for me the performance for AutoDetectChanges=true was a lot worse while saving then this code above. Apart from that I hat my entities not tracked (.AsNoTracking()) so it claimed that all the columns were changed, when I overwrote the db-entry. Jan 31 at 11:54
0

This is way I did it, assuming the new object has more columns to update that the one we want to keep.

                if (theClass.ClassId == 0)
                {
                    theClass.CreatedOn = DateTime.Now;

                    context.theClasses.Add(theClass);
                }
                else {
                    var currentClass = context.theClasses.Where(c => c.ClassId == theClass.ClassId)
                        .Select(c => new TheClasses {
                            CreatedOn = c.CreatedOn
                            // Add here others fields you want to keep as the original record
                        }).FirstOrDefault();
                    theClass.CreatedOn = currentClass.CreatedOn;

                    // The new class will replace the current, all fields
                    context.theClasses.Add(theClass);
                    context.Entry(theClass).State = EntityState.Modified;
                }
                context.SaveChanges();
0

In EF you can do like this

var result = db.Person.Where(x => x.ID == model.ID).FirstOrDefault();
if(result != null){
   result.Name = newName;
   result.DOB = newDOB;
   db.Person.Update(result);
}

Or you can use

using (var db= new MyDbContext())
{
   var result= db.Person.Where(x => x.ID == model.ID).FirstOrDefault();
    result.Name= newName;
    result.DOB = newDOB;
    db.Update(result);
    db.SaveChanges();
 }

For more detail please EntityFramework Core - Update Only One Field

-4

No Worry guys Just write raw sql query

db.Database.ExecuteSqlCommand("Update Person set Name='"+_entity.Name+"' where Id = " + _entity.ID + "");
2
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jan 29, 2022 at 9:22
  • 1
    This could open your application to SQL injection. Use parameters at the very least. Apr 18, 2022 at 21:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.