asp.net-core - 原始 SQL 如何针对 Entity Framework Core 上下文运行?

标签 asp.net-core entity-framework-core asp.net-core-3.1

我已经使用 Entity Framework 很长时间了,但有一个边缘情况需要使用 SQL。我想知道是否可以使用现有的 Entity Framework Core 上下文来实现此目的。这是我目前所拥有的,但运行后,queryResults 变量包含一个“-1”值,而不是学生列表:

string tableName = "Students";
var queryResults = db.Database.ExecuteSqlRaw(@"SELECT * FROM {0}", tableName);

有什么想法吗?


  • Entity Framework Core 3.1
  • .NET Core 3.1
  • Linq 到 SQL

最佳答案

“我想知道是否可以使用现有的 Entity Framework Core 上下文来实现此目的”:

是的,您可以使用现有的databaseContext,但您必须在dbContext实体上执行该查询,请参阅下面的示例:

var sqlCommand = $"SELECT * FROM Students";
var executeSQL = await _context.Students.FromSqlRaw(sqlCommand).ToListAsync();
return Ok(executeSQL);

输出:

enter image description here

Note: As you can see I am executing sqlCommand on Students dbContext this is valid. But using DbContext you cannot pass the table name dynamically. You must need to define it explicitly.

希望以上步骤能够指导您,您可以查看official document for more details here

使用 Ado.Net 连接更新:

     using (var connection = _context.Database.GetDbConnection())
            {
                connection.Open();
                var tableName = "Students";
                List<Student> _listStudent = new List<Student>();
                var command = connection.CreateCommand();
                command.CommandType = CommandType.Text;
                command.CommandText = string.Format("SELECT * FROM [{0}];", tableName);
                SqlDataReader reader = (SqlDataReader)command.ExecuteReader();
                while (reader.Read())
                {
                    var student = new Student(); // You have to bind dynamic property here based on your table entities
                    student.FirstName = reader["FirstName"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
                    student.LastName = reader["LastName"].ToString();
                    _listStudent.Add(student);

                }
                reader.Close();
                command.Dispose();
                connection.Close();

            }

关于asp.net-core - 原始 SQL 如何针对 Entity Framework Core 上下文运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71917248/

相关文章:

c# - Linq Any() 抛出错误 : String was not recognized as a valid boolean

c# - 在 Docker 容器中访问 .NET Core 项目中的 CSV 文件

c# - 在不加载的情况下按条件更新数据库表中的字段

c# - 我的基本实体未加载到扩展方法中的原因可能是什么?

c# - 模拟 EF 核心 dbcontext 和 dbset

asp.net-core - Azure 应用服务上的 500.31 ANCM 故障排除

regex - 如何使用 FluentValidation 创建强密码?

c# - ASP.NET-Core 应用程序根目录中的 NLog 日志文件

c# - 如何在 ASP.NET Core MVC 的自定义记录器中正确实现 ILogger.IsEnabled()

c# - 具有Docker容器的MVC Net Core的好处