Search code examples
c#entity-frameworkentity-framework-plus

Only update specific column using Z.EntityFramework.Plus' SingleUpdate method


In my project, I want to update a specifiy data set's column using Z.EntityFramework.Plus. I'm using the following code:

await db.Features.SingleUpdateAsync(new Feature()
{
    ID = featureInfo.ID,
    Unit = unit,
});

The Feature class consists of multiple columns. I only want to update the Unit column for a given ID. However, this statement always tries to reset all the other columns to null. So I think that I've misunderstood how this method works in general.

How can I update only the given unit value without modifying (or having to load) all the other values?


Solution

  • You can achieve it by using the Where and UpdateFromQuery:

    await db.Features.Where(x => x.ID == featureInfo.ID).UpdateFromQuery(x => new Feature()
    {
        Unit = unit
    });
    

    For multiple IDs, if the unit is a constant:

    await db.Features.Where(x => ids.Contains(x.ID)).UpdateFromQuery(x => new Feature()
    {
        Unit = unit
    });
    

    If you have thousand/million IDs, is also possible to use the WhereBulkContains method (this one is not free):

    await db.Features.WhereBulkContains(ids).UpdateFromQuery(x => new Feature()
    {
        Unit = unit
    });
    

    EDIT: Answer Comment

    Is there any documentation for the SingleUpdateAsync method I was using

    There is no documentation. It works exactly like BulkUpdate but allows you to pass a single entity instead of a list (this is the only difference).