代码之家  ›  专栏  ›  技术社区  ›  Boris Dabetic

实体LINQ查询变慢

  •  -1
  • Boris Dabetic  · 技术社区  · 6 年前

    我是C#新手,我有一个其他人设计的数据库,query工作得很好,但与SQL相比,它慢了10倍。

    我确实犯过错误,任何人都有加快速度的建议。此模型用于在表中显示,并且我正在转换 int ENUM 以及计算显示折扣。

    代码为:

    var results = from w in db.Washes.AsEnumerable()
                  join t in db.Wash_Types.AsEnumerable() on w.WashTypeId equals t.Id
                  join a in db.Accounts.AsEnumerable() on w.AccountId equals a.Id
                  orderby w.Id descending
                  select new AllWashesTable
                        {
                            Id = w.Id,
                            WashTime = w.WashTime,
                            WashTimeEnd = w.WashTimeEnd,
                            Name = a.Name,
                            Client = (w.Client != null ? w.Client.Naziv : ""),
                            MobileNumber = a.MobileNumber,
                            Identification = w.Identification,
                            WashType = WashTypeShowEnum.WashTypeShowEnumToString((WashTypeShowEnum.WashType) w.WashTypeId),
                            Price = int.Parse(t.WashPrice) * (1 - w.Discount) + "",
                            Discount = w.Discount
                        };
    return results.ToList();
    

    似乎我所有的实体查询都比SQL慢至少5倍以上。在某个地方我犯了一些错误。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Ofir Winegarten    6 年前

    你的问题是 AsEnumerable . 当执行查询时(在您的情况下 results.ToList() ),之后显示的所有内容都将使用linq to objects进行计算。这意味着DB不会处理您的连接。您将从表中获取所有记录。

    但是,您的功能 WashTypeShowEnum.WashTypeShowEnumToString 实体框架不会识别。

    您可能需要移动 A可计算 直到最后,然后 select 结果。

    var results = (from w in db.Washes
                  join t in db.Wash_Types on w.WashTypeId equals t.Id
                  join a in db.Accounts on w.AccountId equals a.Id
                  orderby w.Id descending
                  select new {w, a, t}).AsEnumerable().Select(arg=> new AllWashesTable
                        {
                            Id = arg.w.Id,
                            WashTime = arg.w.WashTime,
                            WashTimeEnd = arg.w.WashTimeEnd,
                            Name = arg.a.Name,
                            Client = (arg.w.Client != null ? arg.w.Client.Naziv : ""),
                            MobileNumber = arg.a.MobileNumber,
                            Identification = arg.w.Identification,
                            WashType = WashTypeShowEnum.WashTypeShowEnumToString((WashTypeShowEnum.WashType) arg.w.WashTypeId),
                            Price = int.Parse(arg.t.WashPrice) * (1 - arg.w.Discount) + "",
                            Discount = arg.w.Discount
                        };
    return results.ToList();