zoukankan      html  css  js  c++  java
  • Entity Framework Core To SQL问题

    APP用户反馈应用反应慢, 经排查发现提现状态刷新服务占用带宽过高. 跟踪问题发现是有一SQL语句

     SELECT `o`.`Id`, `o`.`Amount`, `o`.`AuditedStatus`, `o`.`Createtime`, `o`.`FromUserId`, `o`.`IsDelete`, `o`.`ItemName`, `o`.`OrderNum`,
    `o`.`RelatedId`, `o`.`StatId`, `o`.`TaxAmout`, `o`.`Type`, `o`.`UserId`, `o`.`WithdrawStatus`, `o`.`WithdrawedAmout`
    FROM `financeincomeexpensesoverview` AS `o`
    WHERE `o`.`Amount` > 0.0;
    

    拉取所有提现数据导致.

    检查代码未发现这种查询, 找出可能会产生此SQL代码如下:

    var incomes = await db.Financeincomeexpensesoverview.Where(o => o.RelatedId == WithdrawRelatedId && GetItmeTypesFromType(type).Contains(o.Type) && o.Amount > 0).ToListAsync();

    猜测是EF Core 在linq to sql时出现问题, 查阅Entity Framework Core 文档得到答案:

    当在linq语句中出现无法转换为SQL辅助方法时, 会将除去无法转换SQL的语句执行查询将数据拉入内存然后执行剩余无法转换的部分, 文档中称为Client evaluation.

    上述语句中RelatedId为可空int类型WithdrawRelatedId为int类型,Type为可空类型GetItmeTypesFromType(type)为List类型, 无法将类型转换变为SQL. 所以实际代码执行如下:

    var incomes = await db.Financeincomeexpensesoverview.Where(o => o.Amount > 0).ToListAsync();
    
    incomes = await incomes.Where(o => o.RelatedId == WithdrawRelatedId && GetItmeTypesFromType(type).Contains(o.Type)).ToListAsync();
    

    设置关闭Client evaluation

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    
    {
    
       optionsBuilder
           .UseSqlServer(@"Server=(localdb)mssqllocaldb;Database=EFQuerying;Trusted_Connection=True;")
           .ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
    
    }
    

    可得出转换错误:

    Warning as error exception for warning 'Microsoft.EntityFrameworkCore.Query.QueryClientEvaluationWarning': The LINQ expression 'where (([o].RelatedId == Convert(__WithdrawRelatedId_0, Nullable`1)) AndAlso {__GetItmeTypesFromType_1 => Contains(Convert(ToInt32(Convert([o].Type, Object)), Nullable`1))})' could not be translated and will be evaluated locally. To suppress this Exception use the DbContextOptionsBuilder.ConfigureWarnings API. ConfigureWarnings can be used when overriding the DbContext.OnConfiguring method or using AddDbContext on the application service provider.
    

    Entity Framework Core 文档地址: https://docs.microsoft.com/en-us/ef/core/querying/client-eval

  • 相关阅读:
    JavaScript设计模式与开发实践——读书笔记1.高阶函数(下)
    JavaScript设计模式与开发实践——读书笔记1.高阶函数(上)
    js 去除字符串中的空格
    js 运算符 || && 妙用
    判断一个js对象是不是数组
    Javascript中的异步
    js异步处理工作机制(setTimeout, setInterval)
    移动端html页面优化
    编写高效的jQuery代码
    JavaScript学习笔记 isPrototypeOf和hasOwnProperty使用区别
  • 原文地址:https://www.cnblogs.com/qingyanxiaochen/p/11091400.html
Copyright © 2011-2022 走看看