0

我有一个列名列表,我想动态更新表并将这些列的所有行设置为 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();
}

我还在使用带有 EF 6 的动态 LINQZ 框架。有没有办法动态更新表的某些列? (我也可以构造 sql 更新字符串执行为 CommandText,但我试图避免这种情况)

4

1 回答 1

1

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

UpdateFromQuery类似于UpdateEF Extensions 允许使用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);
于 2021-03-26T13:11:56.823 回答