使用动态LINQ动态更新表



我有一个列名列表,我想动态更新表,并将这些列的所有行设置为NULL。当前代码使用if逻辑,当列列表更改时需要不断更新

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();
}

我还在EF6中使用动态LINQ和Z框架。有没有一种方法可以动态更新表中的某些列?(我也可以构造sql更新字符串作为CommandText执行,但我正在努力避免这种情况(

免责声明:我是项目Entity Framework Plus 的所有者

类似于EF扩展中的UpdateUpdateFromQuery允许使用ExpandoObjectIDictionary<string, object>

例如:

Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("FirstName", null);
dbContext.Users
.Where(x=>x.ParentID = 1234)
.UpdateFromQuery(dict);

下周,Update方法也会支持它,我会在这个时候更新我的答案。

更新

自v5.1.29以来,Update方法还支持字典

Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("FirstName", null);
dbContext.Users
.Where(x=>x.ParentID = 1234)
.Update(dict);

最新更新