微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc – 在ASP.NET MVC中执行原始SQL查询,数据库优先模式

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

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

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

解决方法

Entity Framework Code First API包含的方法使您可以将sql命令直接传递给数据库.您有以下选择:

•对返回实体类型的查询使用DbSet.sqlQuery方法.返回的对象必须是DbSet对象所期望的类型,并且除非您关闭跟踪,否则它们将由数据库上下文自动跟踪. (请参阅以下有关AsNoTracking方法的部分.)

•对返回非实体类型的查询使用Database.sqlQuery方法.即使您使用此方法检索实体类型,数据库上下文也不会跟踪返回的数据.

•对非查询命令使用Database.ExecutesqlCommand.

Calling a Query that Returns Entities:

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);
}

Calling a Query that Returns Other Types of Objects:

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());
}

Calling an Update Query:

[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).希望这有助于……

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐