LINQ到实体包括+何处方法 [英] LINQ To Entities Include + Where Method

查看:134
本文介绍了LINQ到实体包括+何处方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有N×N个表,试想:

I have NxN table, imagine:

用户(ID,...)< - UserAddresses(ID,用户ID addressId,启用,...) - >地址(ID,...)

User(id, ...) <- UserAddresses(id, userId, addressId, enabled, ...) -> Addresses(id, ...)

UserAddresses包含FK用户并解决。 对于我所知道的,在实体框架用户创建的实体,包含集合UserAddresses。地址包含一个集合UserAddresses,和一个特定UserAddress包含一个refenrece到用户和一个地址。

UserAddresses contains the FK to user and to address. For what I know, the Entity created by the Entity Framework User, contains a collection to UserAddresses. The Address contains a collection to UserAddresses, and a specific UserAddress contains one refenrece to User and to one Address.

现在我想要通过LINQ的下一个查询。 对于一个特定的用户ID,只得到启用标志设置好的为true userAddresses。 对于一个特定的用户ID,userAddresses可以包含多个条目,但只有一个被设置好的为这个特定用户。

Now I want to make the next query by linq. For a specific user id, get only the userAddresses with enabled flag setted to true. For a specific user id, userAddresses can contain multiple entries but only one is setted for this specific user.

我可以做的查询是:

context.User.Include( x => x.UserAddresses )
            .Include( x => x.UserAddresses.Select(y => y.Address) )
            .Single( x => x.id == USER_ID )

但我真正想要的是不加载的所有UserAddresses该用户......只有一个包含启用后,设置好的为TRUE!

but what i really want is not to load all UserAddresses for that user... Only the one that contains enabled, setted to TRUE!

有人可以帮助我做这个查询?

Somebody can help me to do this query?

推荐答案

有没有办法在EF以部分加载的关联性。尽量选择到一个匿名类型仅在需要时采取:

There is no way in EF to partially load an association property. Try selecting into an anonymous type to take only what you need:

var result = context.User
   .Where(u => u.Id == userId)
   .Select(u => new {
       Addresses = u.UserAddresses.Select(ua => ua.Address)
            .Where(a => a.Enabled),
       User = u // if you need this as well 
   })
   .Single();

这将不会加载result.User.UserAddresses,但result.Addresses将有你想要什么。

This won't load result.User.UserAddresses, but result.Addresses will have exactly what you want.

如果你真的想回到一切为用户类的一部分,你需要分离result.User,然后更新result.User.UserAddresses指向result.Addresses。

If you really want to return everything as part of the User class, you'd need to detach result.User and then update result.User.UserAddresses to point to result.Addresses.

这篇关于LINQ到实体包括+何处方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆