实体框架核心的性能 [英] Performance of Entity Framework Core

查看:93
本文介绍了实体框架核心的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对EF Core非常陌生.我一直使用EF 6.0,而不必使用包含.现在问题来了,我应该如何处理这些包括在内的问题.我想出了三个可能的选择,想知道您最想使用/哪个是最快的,为什么?

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?

在这些样本中,我的目的是获取俱乐部的详细信息.我想检查一个具有相应ID的俱乐部是否存在,然后获取全部信息.

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.

选项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();
}

选项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();
}

选项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);
}

推荐答案

让我们从最坏到最好:

  • 选项3 :这显然是最糟糕的.您正在将整个项目下载到内存中,只是为了扔掉它.这是浪费资源.
  • 选项1 :这不是最佳方法,因为您正在对数据库执行2个查询,一个查询用于Count,另一个查询用于SingleOrDefault.不需要第一个,因此:
  • 选项2 :这是最好的情况,因为如果该项目不存在,则不会从数据库下载任何内容,因此您不必为此担心,它也是一个数据库调用.
  • 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.

这篇关于实体框架核心的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆