2014-09-13 14 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

相關問題