Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 663
André Reichelt Avatar asked Jan 19 '26 17:01

André Reichelt


1 Answers

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).

like image 125
Jonathan Magnan Avatar answered Jan 22 '26 08:01

Jonathan Magnan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!