2014-09-13 30 views
0

我正在用C#编写一个使用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 
    } 
} 

感谢,任何帮助,将不胜感激。

+0

你想要返回一列,而不是“员工”对象列表? – 2014-09-13 11:45:32

+0

是的,基本上。 – iMix 2014-09-13 12:18:01

回答

0

让我们假设你的目标列是一个字符串,暂时。然后你的语法是这样的:

// 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#没有办法让int#的属性类型变为intind。你可能不得不使用一些特殊的逻辑。

另一种方式来做到这一点,顺便说一下,不涉及构建自定义的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(); 
+0

在我写完这篇文章之后,我想到了另一种方法,涉及将属性表达式传递给您的方法,该方法会告诉LINQ您想要的“employee”的属性。这将比反射会更快。让我知道你是否想要更多信息。 – 2014-09-15 12:59:16

相关问题