How to include related tables in DbSet.Find()?

后端 未结 2 1891
梦毁少年i
梦毁少年i 2021-01-13 20:06

If I want to include related objects in an EF7 query, it\'s nice and easy:

var myThing = db.MyThings
                .Include(t => t.RelatedThing)
                


        
2条回答
  •  暖寄归人
    2021-01-13 20:33

    It was not possible with EF6, I don't think EF Core will change that. This is because the main purpose of the Find method is to bring the already loaded entity from the local cache, or load it from the database if it's not there. So the eager loading (Include) can be used only in the later case, while in the former it would need to perform explicit loading. Combining both in a single method might be technically possible, but is hard.

    I think you should take the FirstOrDefault (or SingleOrDefault) route combined with eager loading. You can see a sample implementation for EF6 in Repository generic method GetById using eager loading. It could be adjusted for EF Core like using the dbContext.Model.FindEntityType(typeof(T)).FindPrimaryKey().Properties to find the PK properties and build the predicate. Also since EF Core includes are bit more complicated (require Include / ThenInclude chains), you might find interesting this thread Can a String based Include alternative be created in Entity Framework Core?.

提交回复
热议问题