Linq2SQL 获取动态选择列的值
Linq2SQL get value of dynamically chosen column
我有一个 POCO class 描述我的模型:
public class Example
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
}
我想做的是一种扩展方法,使用 Entity Framework DbSets:
以这种方式投影我的 class
var qry = db.Examples.Select(x => new {
Prop1 = x.Prop1,
Prop2 = x.Prop2,
Prop3 = x.Prop3,
Description = XXXXX
}).ToList();
其中 XXXXX 是 Prop1、Prop2 或 Prop3 的值 属性,我现在仅在运行时将其命名为字符串。
我不能使用 Dynamic Linq,因为我的目标是 Entity Framework 核心,而且我对 LINQ 表达式越来越着迷,我认为我离解决方案还很远...
能否请您提供一些指导?
当您显式获取 Description
的所有需要的属性时,您可以在没有 Description
的情况下获取查询,然后从加载的数据生成所需的查询。
假设设置Description
的属性名称存储在name
变量中:
var qry1 = db.Examples.Select(x => new {
Prop1 = x.Prop1,
Prop2 = x.Prop2,
Prop3 = x.Prop3,
}).ToList();
var qry = qry1.Select(x => new {
Prop1 = x.Prop1,
Prop2 = x.Prop2,
Prop3 = x.Prop3,
Description = name == "Prop1"? x.Prop1 : name == "Prop2"? x.Prop2: x.Prop3
}).ToList();
如果您不喜欢对名称进行硬编码,可以使用反射来获取值:
Description = GetProp(x, name)
其中 GetProp
是:
private string GetProp(object y, string name)
{
return y.GetType().GetProperty(name).GetValue(y).ToString();
}
我有一个 POCO class 描述我的模型:
public class Example
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
}
我想做的是一种扩展方法,使用 Entity Framework DbSets:
以这种方式投影我的 classvar qry = db.Examples.Select(x => new {
Prop1 = x.Prop1,
Prop2 = x.Prop2,
Prop3 = x.Prop3,
Description = XXXXX
}).ToList();
其中 XXXXX 是 Prop1、Prop2 或 Prop3 的值 属性,我现在仅在运行时将其命名为字符串。
我不能使用 Dynamic Linq,因为我的目标是 Entity Framework 核心,而且我对 LINQ 表达式越来越着迷,我认为我离解决方案还很远... 能否请您提供一些指导?
当您显式获取 Description
的所有需要的属性时,您可以在没有 Description
的情况下获取查询,然后从加载的数据生成所需的查询。
假设设置Description
的属性名称存储在name
变量中:
var qry1 = db.Examples.Select(x => new {
Prop1 = x.Prop1,
Prop2 = x.Prop2,
Prop3 = x.Prop3,
}).ToList();
var qry = qry1.Select(x => new {
Prop1 = x.Prop1,
Prop2 = x.Prop2,
Prop3 = x.Prop3,
Description = name == "Prop1"? x.Prop1 : name == "Prop2"? x.Prop2: x.Prop3
}).ToList();
如果您不喜欢对名称进行硬编码,可以使用反射来获取值:
Description = GetProp(x, name)
其中 GetProp
是:
private string GetProp(object y, string name)
{
return y.GetType().GetProperty(name).GetValue(y).ToString();
}