C#实体框架-如何获取指定为参数的列
我当时正在用C#编写一个方法,使用的是针对MySQL的ADO.NET实体框架。我在做一个函数,当调用函数时,我指定要选择的列,有点像这样:C#实体框架-如何获取指定为参数的列,c#,mysql,entity-framework,C#,Mysql,Entity Framework,我当时正在用C#编写一个方法,使用的是针对MySQL的ADO.NET实体框架。我在做一个函数,当调用函数时,我指定要选择的列,有点像这样: public string GetColumn(string whereValue, string column) { xxxEntities data = new xxxEntities(); lock (lockObject) { var result = data.employees.SqlQuery("SELECT `" + co
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
所以您想返回一列,而不是
employee
对象的列表?在我写了这篇文章之后,我想到了另一种方法,将一个属性表达式传递给您的方法,告诉LINQ您想要employee
的什么属性。这将比反射更快。如果您想了解更多信息,请告诉我。
var result = data
.employees
.SqlQuery<int>("SELECT `" + column + "` FROM `employees` WHERE `Code` = @p0", code);
// 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();