ef core原始sql查询

ef core用原始sql查询,不能自动映射到类型中。
处理主要是将sql查询结果转换为json,然后再将json转换为类型对象

      public async Task<List<Warning_log>> GetStatData()
      {
          string sql = @"SELECT       
    CONVERT(date, [trigger_time]) as trigger_time
,count(distinct[warning_txt]) as P
,[warning_target]
          FROM  [warning_log] 
group by CONVERT(date, [trigger_time]) ,[warning_target] ";
          var db = GetNewDbContext();

          var jsonObj = await db.Database.SqlQueryRaw<string>($"{sql}   for json path ").ToListAsync();
          string json = jsonObj.First().ToString();         
          var list2 = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Warning_log>>(json);

          return list2;
      }

参考资料
https://stackoverflow.com/questions/74876446/error-in-sqlquery-method-is-not-natively-supported-by-your-database-provider

你可能感兴趣的:(EF,Core,sql,ef,core)