2013-12-12 48 views
2

我有以下查詢和代碼正在運行,我希望在KeyValuePair上返回兩列。我看到返回的總行數是正確的,但所有keyvalue對都是nul!在實體框架上運行原始SQL查詢的KeyValuePair

string query = @"Select id,name from persons"; 

var persons = context.Database.SqlQuery<KeyValuePair<string,string>>(query); 

我看到一個answer說我必須創建一個類來獲得結果;但我的問題是我不能在KeyValuePair上得到結果?或者我必須有一個與屬性匹配的類定義?

回答

2

我相信列名稱需要匹配您正試圖分配給它的某種屬性。

你可以嘗試更改查詢到@"Select id as Key, name as Value from persons";但我認爲這可能是更容易只是創建一個POCO類項目成果轉化

編輯 你不能以這樣的方式使用KeyValuePair因爲:

The type 'System.Collections.Generic.KeyValuePair`2[System.Int32,System.String]' must declare a default (parameterless) constructor in order to be constructed during mapping. 

你應該問自己幾個問題:

  • 爲什麼我使用實體框架時,我寫聯SQL?
  • 爲什麼我沒有可用於存儲此查詢結果的類/結構?

我認爲真正的答案是至少創建一個類來存儲到:

public class Person 
{ 
    public int id { get; set; } 
    public string name { get; set; } 
} 

var persons = context.Database.SqlQuery<Person>(@"Select id, name from persons"); 
+0

我嘗試這樣做,也沒有工作:( – jocull

+0

爲什麼我在使用實體框架時編寫內聯sql?因爲我編寫的SQL有其專家和複雜性。 EF只能做簡單的SQL ... – realPro

3

的問題是,KeyValuePair沒有參數的構造函數。 EF通過首先創建一個對象(通過其無參數構造函數)然後設置其屬性來實現對象。

1

創建對類

public class KeyIntValueString { 
    public int Key { get; set; } 
    public string Value { get; set; } 
} 

然後

string sql = "SELECT RoleId AS [Key], RoleName AS [Value] FROM dbo.webpages_Roles"; 
List<KeyValuePair<int, string>> roles = db.Database.SqlQuery<KeyIntValueString>(sql) 
       .AsEnumerable() 
       .Select(f => new KeyValuePair<int, string>(f.Key, f.Value)) 
       .ToList(); 

和,例如在MVC視圖的情況下,使用KeyValuePair

@model IEnumerable<KeyValuePair<int, string>> 
... 
@foreach (var item in Model) { 
... 
    @Html.DisplayFor(modelItem => item.Key) 
    @Html.DisplayFor(modelItem => item.Value) 
... 
}