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

前端 未结 1 2011
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 20:10

I\'ve been using Entity Framework Profiler to test my data access in an MVC project and have come accross several pages where I\'m making far more db queries than I need to

1条回答
  •  攒了一身酷
    2021-01-14 21:01

    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.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.

    0 讨论(0)
提交回复
热议问题