Using Entity Framework navigation properties without creating lots of queries (avoiding N+1)

巧了我就是萌 提交于 2019-12-01 10:30:25
Ladislav Mrnka

If your entities inherits from EntityObject try to use this:

var members = club.Members.CreateSourceQuery()
                          .Include("Address")
                          .ToList();

If you use POCOs with lazy loading proxies try to use this:

var members = ((EntityCollection<Club>)club.Members).CreateSourceQuery()
                                                    .Include("Address")
                                                    .ToList();

Obviously second version is not very nice because POCOs are used to remove dependency on EF but now you need to convert the collection to EF class. Another problem is that the query will be executed twice. Lazy loading will trigger for Members once to access the property and then second query will be executed when you call ToList. This can be solved by turning off lazy loading prior to running the query.

When you say ActiveClub is shared I believe it means something like it is property in base controller used in derived controllers. In such case you can still use different code in different controller to fill the property.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!