[英]Generic Repository: How to Join List Properties on Same Class
我有一个带有两个列表属性的类,需要由该类的使用者加入。 该类是通过通用存储库检索的。 方法如下:
IList<TEntity> GetAll(params Expression<Func<TEntity, object>>[] navigationProperties);
具有子类/列表属性的类:
public class A
{
// I need to join these 2 in the caller
public IList<B> BList { get; set; } // Bs have an ID property
public IList<C> CList { get; set; } // Cs have an ID property
}
使用(这是我尝试过的):
var x = Repository.GetAll(i=>i.BList)
.Join(Repository.GetAll(i=>i.CList), outerkey => outerkey.???, ...
Intellisense仅显示A类的属性,而不显示B或C的属性。为什么它不显示B和C的ID属性? 我要解决这个错误吗? 这不是一个智能问题。
当前设置中的GetAll
返回A
的列表,我假设填充了关联的B
然后,您尝试将其与填充了C
的另一个 A
列表连接。
我想你想的是一个列表A
s的两个 b
S和c
人口s,然后做一些投影加盟后B
S和C
秒。
我将SelectMany
,首先使用SelectMany
展平连接的B
和C
的列表,然后投影到单个匿名类型
(请注意,我正在为Join
部分使用查询语法,因为在这种情况下,它比方法语法干净得多)
//`A`s with `B`s and `C`s populated
var as = Repository.GetAll(i=>i.BList, i=>i.CList);
var query = as.SelectMany(a => (from b in a.BList
join c in a.CList
on b.Id equals c.Id
select new {b, c}), // get the matching Bs and Cs
(a, bc) => a./*A Property here*/,
bc.b./*B property here*/,
bc.c./*C property here*/)
)
Intellisense有时难以跟上代码编辑器的作用-在带有LINQ的Visual Studio 2013中,我经常看到这一点。 您可以做的一件事是避免类型推断,并在join方法中指定泛型类型参数。 这不是确切的,但是像这样:
...Join<B, C, int, B>(outer => outer.ID, inner => inner.ID, <etc etc>
前两个类型参数分别是外部列表和内部列表的类型(在您的情况下为B和C)。 第三个是密钥的类型(即ID)。 最后一个是结果的类型。 如果您想为此使用匿名类型,那么可悲的是您必须使用类型推断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.