当前位置: 移动技术网 > IT编程>开发语言>.net > EF core的原生SQL查询以及用EF core进行分页查询遇到的问题

EF core的原生SQL查询以及用EF core进行分页查询遇到的问题

2019年10月18日  | 移动技术网IT编程  | 我要评论

火烧红莲寺国语,爱思益,聂卫平人生九局

在用.net core进行数据库访问,需要处理一些比较复杂的查询,就不得不用原生的sql查询了,然而ef core 和ef6 的原生sql查询存在很大的差异。

在ef6中我们用sqlquery和executesqlcommand进行sql语句的执行,而在ef core中我们则使用fromsql和executesqlcommand

一.executesqlcommand(这两者没什么太大的区别)

        company08entities db = new company08entities();
        string sql = string.format("update cars set ispub='是',pubtime='{1}' where id in ({0})",ids,datetime.now);
            int res = db.database.executesqlcommand(sql);    //返回受影响的行数
            if (res>0)
            {
                return json(new uiresult(true,"发布成功!"));
            }
            else
            {
                return json(new uiresult(false,"发布失败,请重试!"));
            }

二.数据库查询语句两者的差别就太大了,这里我会详细举例说明

  1.在ef6中使用sqlquery进行查询以及联和linq进行分页

          company08entities db = new company08entities();
          string sql = "select c.* from cars c join rescommend r on c.id=r.resid where r.posld=2 and deadline>getdate() and c.ispub='是'";var res = db.database.sqlquery<cars>(sql);
                var list = res.skip((pn - 1) * pz).take(pz).tolist();    //其中pn为页码,pz为页大小

  2.在ef core中我们使用fromsql

      private company08context db = null;
        public productcontroller(company08context context)
        {
            this.db = context;
        }
       string sql =string.format($"select c.* from cars c join rescommend r on c.id=r.resid where r.posld=2 and deadline>getdate() and c.ispub='是'");
            
                var res = db.cars.fromsql(sql);

                var list = res.skip((pn-1)*pz).take(pz).tolist();
               

    这中使用 linq 运算符在初始的原始 sql 查询基础上进行组合会出现以下这种问题

  

 

 

     这是因为使用 linq 运算符在初始的原始 sql 查询基础上进行组合。 ef core 将其视为子查询,并在数据库中对其进行组合,导致查询出错

    解决方案就是阻止查询运算操作的组合,fromsql 方法之后立即使用 asenumerableasasyncenumerable 方法,确保 ef core 不会尝试对存储过程进行组合。

       string sql =string.format($"select c.* from cars c join rescommend r on c.id=r.resid where r.posld=2 and deadline>getdate() and c.ispub='是'");
                var res = db.cars.fromsql(sql).asenumerable();
             var list = res.skip((pn-1)*pz).take(pz).tolist();

 

  

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网