I have a list of column names and I want to dynamically update table and set all the rows for those columns to NULL. The current code is using if
logic and it need to keep updating when list of columns changes
var columns = new string[] {"FirstName","LastName"};
using(var scope = new TransactionScope())
{
foreach(var col in columns)
{
if(col == "FirstName")
{
dbContext.Users
.Where(x=>x.ParentID = 1234)
.Update(x=> new User()
{
FirstName = null
}
}
if(col == "LastName")
{
dbContext.Users
.Where(x=>x.ParentID = 1234)
.Update(x=> new User()
{
LastName = null
}
}
}
scope.Complete();
}
I am also using Dynamic LINQ and Z Framework with EF 6. Is there a way to update table certain columns dynamically? (I can also construct sql update string execute as CommandText but I am trying to avoid that)
Disclaimer: I'm the owner of the project Entity Framework Plus
The UpdateFromQuery
similar to Update
from EF Extensions allow to uses ExpandoObject
and IDictionary<string, object>
For example:
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("FirstName", null);
dbContext.Users
.Where(x=>x.ParentID = 1234)
.UpdateFromQuery(dict);
Next week, the Update
method will also support it, I will update my answer at this time.
UPDATED
Since the v5.1.29, the Update
method also support dictionary
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("FirstName", null);
dbContext.Users
.Where(x=>x.ParentID = 1234)
.Update(dict);