7

我的项目的模型是数据库优先,并使用远程访问另一台服务器上的数据库。我需要使用原始 SQL 查询,因为我的查询非常复杂,而且我在 SQl 而不是 LINQ 中感觉更舒服。

这就是我的做法:

        string query = "select * from Inquiry_TBL where ...";

        using (educationEntities db = new educationEntities())
        {
            var list = db.Database.SqlQuery<Inquiry_TBL>(query);
            ViewData["total"] = list.Count();
        }

问题是有时我在一秒钟内得到查询结果,有时它只是保持加载很长时间,并给我一个错误,“当数据读取器关闭时调用'读取'不是一个有效的操作。”

这是为什么?我的代码有问题,还是因为我正在使用远程访问另一台服务器?切换到本地服务器会解决问题吗?

4

1 回答 1

11

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)。希望这可以帮助。

于 2015-03-19T14:44:04.460 回答