In straight SQL, I'd probably wrap some logic over a simple join, but how would I do this efficiently in LINQ to SQL? Imagine I have two tables:
在直接的SQL中,我可能会在简单的连接上包含一些逻辑,但是如何在LINQ to SQL中有效地执行此操作?想象一下,我有两张桌子:
Parent
- ID
Child
- ParentID
- ID
- Name
Ideally I'd like a graph of Parent objects with a "Childs" property that is actually a Dictionary<int, string>.
理想情况下,我想要一个带有“Childs”属性的Parent对象的图形,该属性实际上是Dictionary
Suggestions?
2 个解决方案
#1
//set up dataloadoptions
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Parent>(item => item.Child);
context.LoadOptions = options;
var children = context.Parent.First().Child;
#2
Something along the lines of this:
有点像这样:
MyDataContext.Parents
.Select(p =>
new { p.ID,
Childs = p.Children.ToDictionary(c => c.ID, c => c.Name)
}
);
The above will project an anonymous type with two properties: An ID ( being the Parent's) and a Dictionary containing the childrens' ID and Name.
上面将投射一个具有两个属性的匿名类型:一个ID(作为Parent)和一个包含孩子的ID和Name的Dictionary。
#1
//set up dataloadoptions
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Parent>(item => item.Child);
context.LoadOptions = options;
var children = context.Parent.First().Child;
#2
Something along the lines of this:
有点像这样:
MyDataContext.Parents
.Select(p =>
new { p.ID,
Childs = p.Children.ToDictionary(c => c.ID, c => c.Name)
}
);
The above will project an anonymous type with two properties: An ID ( being the Parent's) and a Dictionary containing the childrens' ID and Name.
上面将投射一个具有两个属性的匿名类型:一个ID(作为Parent)和一个包含孩子的ID和Name的Dictionary。