【问题标题】:Performance issue in entity framework实体框架中的性能问题
【发布时间】:2018-08-02 12:07:16
【问题描述】:

我有一些数据库模型:

 public class SomeEntity
    {
        [Key]
        public int Id { get; set; }
        public Schedule Schedule { get; set; }
        public ICollection<Address> Addresses { get; set; }
        public ICollection<Phone> Phones { get; set; }
        public ICollection<Email> Emails { get; set; }
    }

和

public class Schedule
{
    [Key]
    public int id { get; set; }
    public ICollection<TimeRange> Monday { get; set; }
    public ICollection<TimeRange> Tuesday { get; set; }
    public ICollection<TimeRange> Wednesday { get; set; }
    public ICollection<TimeRange> Thursday { get; set; }
    public ICollection<TimeRange> Friday { get; set; }
    public ICollection<TimeRange> Saturday { get; set; }
    public ICollection<TimeRange> Sunday { get; set; }
}

当我跑步时:

 var entity = _dbContext.SomeEntity
                .Include(p => p.Addresses)
                .Include(p => p.Emails)
                .Include(p => p.Phones)
                .Include(p => p.Schedule)
                .ThenInclude(s => s.Monday)
                .Include(p => p.Schedule)
                .ThenInclude(s => s.Tuesday)
                .Include(p => p.Schedule)
                .ThenInclude(s => s.Wednesday)
                .Include(p => p.Schedule)
                .ThenInclude(s => s.Thursday)
                .Include(p => p.Schedule)
                .ThenInclude(s => s.Friday)
                .Include(p => p.Schedule)
                .ThenInclude(s => s.Saturday)
                .Include(p => p.Schedule)
                .ThenInclude(s => s.Sunday)
            return entity;

执行需要很长时间。我该如何解决这个问题?

【问题讨论】:

  • 您应该使用数据库索引,并且您可能还想应用 .Where 子句,因为现在您正在从其他表中获取 SomeEntity 的所有行及其所有相关值。
  • 即使使用.FirstOrDefault(p =&gt; p.Id == id); 也需要大约 4162 毫秒
  • 回答这个问题需要你的表定义+索引定义。还要指定您使用的 DBMS 或数据源(Access?Excel?MySQL?Oracle?Sql Server?)删除不太相关的标签并添加适当的 DBMS 标签。
  • 您不能一直添加Includes 并期望查询保持快速。看起来模型的Schedule 部分需要进一步规范化。度过所有这些不同的日子看起来不太好。
  • 您好,您有想要在 LINQ 和 EF Core 中实现的正确 sql 查询吗?从我看到这个语句创建了很多 JOINS 并且没有适当的原始 sql 语句我不认为有很多事情可以帮助你。

标签: mysql .net-core entity-framework-core dbcontext asp.net-core-webapi


【解决方案1】:

你有太多的包含。目前没有直接优化它的选项(包含过滤器将在 ef core 2.1 的下一个版本中)。如果你真的需要所有这些数据,你应该使用 rawquery。

【讨论】:

    猜你喜欢
    • 2011-11-16
    • 2016-03-09
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多