Raw SQL Query without DbSet - Entity Framework Core

后端 未结 17 1422
眼角桃花
眼角桃花 2020-11-22 13:27

With Entity Framework Core removing dbData.Database.SqlQuery I can\'t find a solution to build a raw SQL Query for my full-text search query th

17条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 13:57

    For now, until there is something new from EFCore I would used a command and map it manually

      using (var command = this.DbContext.Database.GetDbConnection().CreateCommand())
      {
          command.CommandText = "SELECT ... WHERE ...> @p1)";
          command.CommandType = CommandType.Text;
          var parameter = new SqlParameter("@p1",...);
          command.Parameters.Add(parameter);
    
          this.DbContext.Database.OpenConnection();
    
          using (var result = command.ExecuteReader())
          {
             while (result.Read())
             {
                .... // Map to your entity
             }
          }
      }
    

    Try to SqlParameter to avoid Sql Injection.

     dbData.Product.FromSql("SQL SCRIPT");
    

    FromSql doesn't work with full query. Example if you want to include a WHERE clause it will be ignored.

    Some Links:

    Executing Raw SQL Queries using Entity Framework Core

    Raw SQL Queries

提交回复
热议问题