我需要在樹上表示數據,每個節點有id
,text
和attributes
。LINQ to Entities - 初始化複雜對象(Dictionary或List <KeyValuePair>)
我試過讓我的attributes
屬性通用,並使用LINQ to Entities進行初始化。
嘗試1:
隨着我的課爲:
public class TreeNode
{
public int id { get; set; }
public string text { get; set; }
public Dictionary<string, object> attributes { get; set; }
public int? parent { get; set; }
}
我試着初始化:
List<TreeNode> taskItems = new List<TreeNode>();
using (var database = new MyDatabase())
{
taskItems =
(
from t in database.Task
select new TreeNode()
{
id = t.ID,
text = t.Name,
attributes = new Dictionary<string, object>()
{
{ "Color", t.Color },
{ "Category", t.Category }
},
parent = t.ParentID
}
)
.ToList();
}
上述失敗,出現錯誤
LINQ to Entities支持只列出具有單個元素的初始化程序項目。
嘗試2:
我試圖List<KeyValuePair>
代替Dictionary
:
public class TreeNode
{
public int id { get; set; }
public string text { get; set; }
public List<KeyValuePair<string, object>> attributes { get; set; }
public int? parent { get; set; }
}
我試圖初始化:
List<TreeNode> taskItems = new List<TreeNode>();
using (var database = new MyDatabase())
{
taskItems =
(
from t in database.Task
select new TreeNode()
{
id = t.ID,
text = t.Name,
attributes = new List<KeyValuePair<string, object>>()
{
new KeyValuePair<string, object>("Color", t.Color),
new KeyValuePair<string, object>("Category", t.Category)
},
parent = t.ParentID
}
)
.ToList();
}
這一次上述失敗,錯誤
只有參數構造函數初始化和LINQ中支持到實體。
我如何能實現attributes
屬性的初始化?
[本SO](https://stackoverflow.com/questions/35014278/how-to-create-a-dictionary-in-linq -when-populating-a-class/35014914)應該對你有所幫助。 –