问题描述
我有一个列名列表,我想动态更新表并将这些列的所有行设置为 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 中使用 Dynamic LINQ 和 Z Framework。有没有办法动态更新表的某些列? (我也可以构造 sql 更新字符串作为 CommandText 执行,但我试图避免这种情况)
解决方法
免责声明:我是项目Entity Framework Plus
的所有者类似于 EF 扩展中的 UpdateFromQuery
的 Update
允许使用 ExpandoObject
和 IDictionary<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,null);
dbContext.Users
.Where(x=>x.ParentID = 1234)
.Update(dict);