[英]Entity Framework: How to select nested entity
my entity hierarchy is Customer > Address > Contact. 我的实体层次结构是客户>地址>联系人。 so i use this code to iterate in contact details.
因此,我使用此代码来迭代联系方式。
Contacts CurrentContacts = null;
foreach (var existingContacts in existingCustomer.Addresses.Select(a => a.Contacts.Where(cc=> cc.ContactID==5)))
{
CurrentContacts = existingContacts;
}
but this line CurrentContacts = existingContacts;
但是此行
CurrentContacts = existingContacts;
throwing error 抛出错误
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'EFTest.Contacts'.
无法将类型'System.Collections.Generic.IEnumerable'隐式转换为'EFTest.Contacts'。 An explicit conversion exists (are you missing a cast?)
存在显式转换(您是否缺少演员表?)
what is my mistake. 我有什么错
existingContacts
will have contacts related data and CurrentContacts
is a variable of contact type. existingContacts
将具有与联系人相关的数据,而CurrentContacts
是联系人类型的变量。
so please tell me how could i do it. 所以请告诉我我该怎么做。
Use SelectMany
instead of Select
. 使用
SelectMany
代替Select
。
Select
projects each individual element and does nothing to the rest of the enumerable . Select
投影每个单独的元素,对其余的枚举不做任何事情。 So Addresses.Select(a=>a.Contacts.Where(...))
is an enumerable of whatever Address.Contacts.Where(...)
is. 所以
Addresses.Select(a=>a.Contacts.Where(...))
可以枚举任何Address.Contacts.Where(...)
。 Ie. 就是 you get an enumerable of enumerables.
您会得到一个可枚举的枚举。
To get a single enumerable you need to flatten this list. 要获得单个枚举,您需要将此列表弄平。 Which is what
SelectMany
does. SelectMany
就是这样做的。
That said even 甚至说
foreach (var existingContacts in <some enumerable>)
{
CurrentContacts = existingContacts;
}
Looks strange. 看起来很奇怪 Unless there are other logic in the loop you could replace the loop with;
除非循环中没有其他逻辑,否则可以将循环替换为;
CurrentContacts= <some enumerable>.LastOrDefault();
And if you don't actually care which Contact you use, as long as it has ContactID=5; 而且,如果您实际上不关心使用哪个联系人,只要它的ContactID = 5即可;
CurrentContacts= <some enumerable>.FirstOrDefault();
I think you have two problems, but without seeing how the Contacts
type is defined it's just a guess. 我认为您有两个问题,但是没有看到
Contacts
类型是如何定义的,这只是一个猜测。
As @Taemyr points out, you need to use SelectMany
instead of Select
to flatten the collection of collections. 正如@Taemyr指出的那样,您需要使用
SelectMany
而不是Select
来展平集合的集合。
But unless Contacts
is inherited from List<EFTest.Contacts>
you still aren't going to be able to do the assignment, you need to change your variable declaration to: 但是除非
Contacts
是从List<EFTest.Contacts>
继承的,否则您仍然无法执行赋值操作,您需要将变量声明更改为:
IEnumerable<Contacts> CurrentContacts = null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.