gpt4 book ai didi

c# - 从字符串列名称动态创建 LINQ Select 表达式

转载 作者:太空狗 更新时间:2023-10-30 00:18:10 25 4
gpt4 key购买 nike

我有一个看起来像这样的方法:

public string GetColVal(string aAcctField, bool callM1, bool callM2)
{
if (callM1)
{
// create select clause here to select a string column with name
// equal to the value of aAcctField from Table1
// Expression<Func<Table1, string>> selector = ?
return M1(selector);
}

if (callM2)
{
// create select clause here to select a string column with name
// equal to the value of aAcctField from Table2
// Expression<Func<Table2, string>> selector = ?
return M2(selector);
}
}

M1() 是这样的:

public string M1(Expression<Func<Table1, string>> columnToSelect, string xType)
{
// other logic
string acct = _cntx.Where(c => c.Type == xType)
.Select(columnToSelect)
.FirstOrDefault();
return acct;
}

M2() 也是类似的东西。请注意,这些方法过于简单。 M1()M2() 方法运行良好。我可以这样调用它们:

// MyColumn is a strongly typed column in Table1
string acct = M1(x => x.MyColumn, "some value");

但是,在方法 GetColVal() 中,我如何构建选择子句?关于 selector 的评论将帮助您理解我打算做什么。所以,请继续阅读评论。

我试过这个:

public string GetColVal(string aAcctField, bool callM1, bool callM2)
{
if (callM1)
{
// create select clause here to select a string column with name
// equal to the value of aAcctField from Table1
Expression<Func<Table1, string>> selector = (w) => w.GetType().GetProperty(aAcctField).Name;
return M1(selector);
}
...
}

我得到了异常:

LINQ to Entities does not recognize the method 'System.Reflection.PropertyInfo GetProperty(System.String)' method, and this method cannot be translated into a store expression

我看过这些:

但它们都不是我所需要的。

最佳答案

基本上你需要使用 Expression类方法,如 Expression.Lambda , Expression.PropertyOrField等构建所需的选择器,如:

static Expression<Func<T, TValue>> MemberSelector<T, TValue>(string name)
{
var parameter = Expression.Parameter(typeof(T), "item");
var body = Expression.PropertyOrField(parameter, name);
return Expression.Lambda<Func<T, TValue>>(body, parameter);
}

要支持嵌套属性,将 var body = ... 行更改为

var body = name.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField);

示例用法:

if (callM1)
{
return M1(MemberSelector<Table1, string>(aAcctField));
}
...

关于c# - 从字符串列名称动态创建 LINQ Select 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41676566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com