Performance of Entity Framework Core

我与影子孤独终老i 提交于 2019-12-11 05:25:54

问题


I'm quite new to the EF Core. I always used the EF 6.0 and never had to use an include. Now the question comes up how i should work with these includes. I figured out three possible options and wanted to know wich would you prefer to use/which is the fastest and why?

In these samples my intention is to get the details of a club. I want to check if a club with the corresponding id exists and then get the whole information.

Option 1:

using (var context = new TrainingSchedulerContext())
{
    var clubs = context.Clubs.Where(c => c.Id == clubId);
    if (clubs.Count() == 0)
        return NotFound();

    var club = clubs.Include(c => c.Memberships)
        .Include(c => c.MembershipRequests)
        .Include(c => c.TrainingTimes)
        .Include(c => c.AdminRoles)
        .SingleOrDefault();
}

Option 2:

using (var context = new TrainingSchedulerContext())
{
    var club = context.Clubs.Include(c => c.Memberships)
            .Include(c => c.MembershipRequests)
            .Include(c => c.TrainingTimes)
            .Include(c => c.AdminRoles)
            .SingleOrDefault(c => c.Id == clubId);

    if (club == null)
        return NotFound();
}

Option 3:

using (var context = new TrainingSchedulerContext())
{
    var club = context.Clubs.SingleOrDefault(c => c.Id == clubId);
    if (club == null)
        return NotFound();

    club = context.Clubs.Include(c => c.Memberships)
        .Include(c => c.MembershipRequests)
        .Include(c => c.TrainingTimes)
        .Include(c => c.AdminRoles)
        .SingleOrDefault(c => c.Id == clubId);
}

回答1:


Let's go from worst to best:

  • Option 3: this is obviously the worst. You are downloading the entire item into memory just for throwing it away. This is a waste of resources.
  • Option 1: this is not the best way because you are executing 2 queries against the database, one for Count and another one for SingleOrDefault. The first one is not needed, hence:
  • Option 2: this is the best case because if the item does not exist, nothing will be downloaded from the database, so you don't have to worry about that, and it's also a single database call.


来源:https://stackoverflow.com/questions/49447231/performance-of-entity-framework-core

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