How to update a single property in Entity Framework Core

entity-framework-core

Question

I need to update only one or two properties of an Entity. In other words, I have an entity with an Id, ParentId, Name, and Description.

The issue is that when the name is updated, the Description is wiped out if it already existed in the database.

This is the code:

internal void Update(ItemInfo itemInfo)
    {
        var item = new Item { Id = itemInfo.Id, ParentId = itemInfo.ParentId, Name = itemInfo.Name };
        var entry = this.DbContext.Items.Attach(item);
        if(item.ParentId!=null) entry.Property(x => x.ParentId).IsModified = true;
        if(!(String.IsNullOrWhiteSpace(item.Name))) entry.Property(x => x.Name).IsModified = true;
        this.SaveChanges();;
    }

I thought that since I was setting the particular property as modified, only that property would be updated.

Or should I be getting the entity from the database first, and then just setting the property and saving. I wanted to avoid two trips to the database for a single save.

1
0
6/10/2018 4:54:51 AM

Accepted Answer

You have to first get the entity first using from database and then update the Entity.

-1
6/10/2018 2:48:50 PM

Popular Answer

You can do following in order to update a single property:

internal void Update(ItemInfo itemInfo)
{
    if (itemInfo == null) { throw new Exception($"item info was not supplied"); }

    var itemInfoEntity = new ItemInfo()
    {
        Id          = itemInfo.Id,
        ParentId    = itemInfo.ParentId,
        Name        = itemInfo.Name 
    };

    dbContext.ItemInfo.Attach(itemInfoEntity);
    dbContext.Entry(itemInfoEntity).Property(x => x.Id).IsModified = true;
    dbContext.Entry(itemInfoEntity).Property(x => x.Id).IsModified = true;
    dbContext.Entry(itemInfoEntity).Property(x => x.Id).IsModified = true;
    dbContext.SaveChanges();
}

But if you only are updating few properties, then I think you should not send the whole object as parameter, just send the properties that needs to be updated something like this:

internal void Update(id, parentId, name)
{
 ...
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow