在ASP.NET MVC中执行原始SQL查询,数据库第一模式

问题描述 投票:5回答:1

我的项目模型是数据库优先,并使用远程访问另一台服务器上的数据库。我需要使用原始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();
        }

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

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

asp.net-mvc razor lazy-evaluation rawsql
1个回答
7
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.