简体   繁体   English

实体框架多对多过滤器

[英]Entity Framework Many to Many Filter

I have a many to many relationship in EF Code First between Contacts and Lists. 在EF Code First中,我在联系人和列表之间有很多关系。 ProxyCreation and LazyLoading are disabled to allow serialization of the entities. 禁用ProxyCreation和LazyLoading以允许序列化实体。

I have a query that is meant to return contacts that are in a given list. 我有一个查询,该查询旨在返回给定列表中的联系人。

// GET api/Contacts
        [Queryable]
        public IQueryable<Contact> GetContacts(int bulkListId)
        {
            var bulkList = db.BulkLists.Include(c => c.Contacts).Where(c => c.ID == bulkListId).SingleOrDefault();

            if (bulkList == null)
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));

            return bulkList.Contacts.AsQueryable().OrderBy(c => c.ID).Include(c => c.AddressBookType).Include(c => c.BulkLists);
        }

Although this works, it doesn't work as intended. 尽管此方法有效,但未按预期工作。 It results in the correct set of contacts who are in a given list but these contacts only have that list populated in their Lists property of the relationship. 它会生成给定列表中的一组正确的联系人,但是这些联系人仅在其关系的Lists属性中填充了该列表。 So when this is serialized and gets back to the client it hides the other lists that the contacts are members of. 因此,当将此序列化并返回到客户端时,它将隐藏联系人所属的其他列表。

I can't see how the query is filtering it in this way and how I might change it to include the full set of lists. 我看不到查询如何以这种方式过滤查询以及如何更改查询以包括完整的列表集。 Any advice would be very much appreciated. 任何建议将不胜感激。

You're cheating! 你在作弊! :) :)

By adding AsQueryable() to bulkList.Contacts you make it possible to continue with Include without making the compiler complain. 通过将AsQueryable()添加到bulkList.Contacts ,可以继续使用Include而不会引起编译器的抱怨。 BUT... 但...

As per MSDN on DbExtensions.Include : 根据DbExtensions.Include上的MSDN

This extension method calls the Include(String) method of the IQueryable source object, if such a method exists . 此扩展方法调用IQueryable源对象的Include(String)方法( 如果存在) If the source IQueryable does not have a matching method, then this method does nothing. 如果源IQueryable没有匹配方法,则此方法不执行任何操作。

(emphasis mine) (强调我的)

And EntityCollection does not have an Include method, so nothing happens. 而且EntityCollection没有Include方法,因此什么也没发生。

You'll have to expand the include list in your first statement, probably like so: 您必须在第一条语句中扩展包含列表,大概是这样的:

db.BulkLists
    .Include(c => c.Contacts.Select(c => c.AddressBookType))
    .Include(c => c.Contacts.Select(c => c.BulkLists))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM