Is there any way to *conditionally* set a property with EF `.ExecuteUpdateAsync()`?
Right now, I'm doing
but I'm not sure how would I do something similar, as in, something that avoids setting
x.Name = x.Name
, with the Execute method. Something like
but no such thing seems to exist.11 Replies
I do not know what you exactly need. However the object is tracked. so if you set the value and it is the same. EF will notice that. Save wont do anything.
Before you save you can use the property in the _ctx to check if there are any changes
var thing = await _ctx.Things.FirstOrDefaultAsync(t => t.Id == req.Id);
thing.Name = req.Name;
thing.Count = req.Count;
await _ctx.SaveChangesAsync(); // only saves if there are any changes. You //can also check for changes using:
if (_ctx.ChangeTracker.HasChanges())
await _ctx.SaveChangesAsync();
Yes, which is why I'm doing it this way
But I'd like to start using the
.Execute
method here to save on a database callthe code below essantial does the same.
The object is taken. The values are updated and no if functions required
var thing = await _ctx.Things.FirstOrDefaultAsync(t => t.Id == req.Id);
thing.Name = req.Name;
thing.Count = req.Count;
if (_ctx.ChangeTracker.HasChanges())
await _ctx.SaveChangesAsync();
you can also use sql commands with EF. but its build for not using sql
_ctx.ExecuteSql
what sql would this translate to, an inline if?
i don't think i have ever seen that but i could be wrong
It would just not add a set clause to the resulting SQL
have you tried if ?: is translated?
Though... I guess it wouldn't know without executing some other query
Just a simple bool would also work, I guess
with just a null condition (on external value) you could make an extension (to add the expression)
In case
req.Name
is null it would generate
If neither is null,
Huh, an extension method on the expression, maybe?that's what i said
Yeah
That could work