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

标签 asp.net-mvc razor lazy-evaluation rawsql

我的项目的模型是数据库优先,并使用远程访问另一台服务器上的数据库。
我需要使用原始 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) .希望这可以帮助。

关于asp.net-mvc - 在 ASP.NET MVC 中执行原始 SQL 查询,数据库优先模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16807334/

相关文章:

c# - 添加 View 或 Controller 时 Visual Studio 2013 获取 AppDomain 时出错

asp.net - 调查问卷中单选按钮的默认状态

R: promise 已在评估中

perl - 有多少种方法可以描述Perl 6中的斐波那契数列?

c# - ASP .NET MVC,创建类似路由配置的永久链接

asp.net - 为什么我的 aspx 页面没有缓存在客户端上?

asp.net-mvc - Kendo DatePicker 文化无法正常工作

jquery - 当文本框中没有任何内容时,如何将下拉列表重置回默认值?

c# - 在布局 View 上填充 ViewBag

haskell - 我的 Haskell 表达式何时计算?