我已经使用 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);
输出:
Note:
As you can see I am executingsqlCommand
onStudents
dbContext
this is valid. But usingDbContext
you cannot pass the table name dynamically. You must need todefine 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/