linq2SQL获取动态选择的列的值

问题描述 投票:0回答:1

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

我想做的是使用实体框架DBSET的扩展方法将我的课程投射:

var qry = db.Examples.Select(x => new { Prop1 = x.Prop1, Prop2 = x.Prop2, Prop3 = x.Prop3, Description = XXXXX }).ToList();

xxxxx是prop1,prop2或prop3属性的值,我只在运行时才称之为字符串。
我无法使用动态LINQ,因为我是针对实体框架核心,而且我对Linq表达式感到疯狂,而且我认为我离解决方案还很远...
您能提供一些指导吗?

当您明确获取所有必需的属性时,您可以在没有

Description
entity-framework linq iqueryable
1个回答
1
投票

评估设置属性的名称

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

where
Description = GetProp(x, name)

是:

GetProp


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.