【发布时间】:2017-05-25 11:30:11
【问题描述】:
我需要在树上表示数据,每个节点都有id、text 和几个attributes。
我已尝试保持我的 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 to Entities 仅支持无参数构造函数和初始化程序。
如何实现attributes属性的初始化?
【问题讨论】:
-
This SO 应该可以帮到你。
标签: c# .net entity-framework linq