Linq2SQL获取动态选择列的值

时间:2016-07-19 17:54:14

标签: entity-framework linq iqueryable

我有一个POCO类描述我的模型:

public class Example
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
}

我尝试做的是使用Entity Framework DbSets以这种方式投影我的类的扩展方法:

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,因为我的目标是实体框架核心,而且我对LINQ表达式感到疯狂,我认为我还远离解决方案...... 你能提供一些指导吗?

1 个答案:

答案 0 :(得分:1)

当您显式获取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();
}