Entity Framework Code First API 包括使您能够将 SQL 命令直接传递到数据库的方法。您有以下选择:
• 对返回实体类型的查询使用 DbSet.SqlQuery 方法。返回的对象必须是 DbSet 对象所期望的类型,并且除非您关闭跟踪,否则它们会被数据库上下文自动跟踪。(有关 AsNoTracking 方法,请参阅以下部分。)
• 对返回非实体类型的查询使用Database.SqlQuery 方法。即使您使用此方法检索实体类型,数据库上下文也不会跟踪返回的数据。
• 将Database.ExecuteSqlCommand 用于非查询命令。
调用返回实体的查询:
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// Commenting out original code to show how to use a raw SQL query.
//Department department = await db.Departments.FindAsync(id);
// Create and execute raw SQL query.
string query = "SELECT * FROM Department WHERE DepartmentID = @p0";
Department department = await db.Departments.SqlQuery(query, id).SingleOrDefaultAsync();
if (department == null)
{
return HttpNotFound();
}
return View(department);
}
调用返回其他类型对象的查询:
public ActionResult About()
{
//Commenting out LINQ to show how to do the same thing in SQL.
//IQueryable<EnrollmentDateGroup> = from student in db.Students
// group student by student.EnrollmentDate into dateGroup
// select new EnrollmentDateGroup()
// {
// EnrollmentDate = dateGroup.Key,
// StudentCount = dateGroup.Count()
// };
// SQL version of the above LINQ code.
string query = "SELECT EnrollmentDate, COUNT(*) AS StudentCount "
+ "FROM Person "
+ "WHERE Discriminator = 'Student' "
+ "GROUP BY EnrollmentDate";
IEnumerable<EnrollmentDateGroup> data = db.Database.SqlQuery<EnrollmentDateGroup>(query);
return View(data.ToList());
}
调用更新查询:
[HttpPost]
public ActionResult UpdateCourseCredits(int? credit)
{
if (credit != null)
{
ViewBag.RowsAffected = db.Database.ExecuteSqlCommand(
"UPDATE Course SET Credits = Credits * {0}", credit);
}
return View();
}
有关更多信息,请查看Advanced Entity Framework 6 Scenarios for an MVC 5 Web Application (12 of 12)。希望这可以帮助。