gpt4 book ai didi

C# Entity Framework - 如何获取指定为参数的列

转载 作者:行者123 更新时间:2023-11-29 23:47:53 24 4
gpt4 key购买 nike

我正在使用 ADO.NET Entity Framework for MySQL 用 C# 编写一个方法。我正在创建一个函数,当调用该函数时,我指定我正在选择的列,有点像这样:

public string GetColumn(string whereValue, string column)
{
xxxEntities data = new xxxEntities();
lock (lockObject)
{
var result = data.employees.SqlQuery("SELECT `" + column + "` FROM `employees` WHERE `Code` = '" + code + "'");
return result.ToListAsync().Result[0].????; // I want to get the column in the parameters
}
}

谢谢,如有任何帮助,我们将不胜感激。

最佳答案

暂时假设您的目标列是一个字符串。那么你的语法将是这样的:

// I've parameterized the parameterizable part of your query
var result = data
.employees
.SqlQuery<string>("SELECT `" + column + "` FROM `employees` WHERE `Code` = @p0", code);
return result.ToListAsync().Result[0]; // Result[0] is a string

如果您的目标列是整数,则第一行将为:

var result = data
.employees
.SqlQuery<int>("SELECT `" + column + "` FROM `employees` WHERE `Code` = @p0", code);

程序不知道 result 需要什么类型,因此您需要通过向 SqlQuery 方法提供类型参数来告诉它。

如果column 可以有不同的类型,那么就会遇到一些问题,因为 C# 无法凭直觉知道属性类型是什么。您可能需要使用一些特殊的逻辑。

顺便说一下,另一种不涉及构建自定义 SQL 的方法是使用 employee 对象进行查询,但使用反射来访问所需的属性:

// Warning:  this is being done from memory. 
var result = data.employees
.Where(e => Code == code);
// Assuming the property is a string:
return result
.Select(e => (string) typeof(employee).GetProperty(column).GetValue(e))
.ToListAsync();

关于C# Entity Framework - 如何获取指定为参数的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25822862/

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