0

如何使用本机查询DBContext?如果我运行代码,这会给我例外。为什么以及如何在使用时运行本机查询DBContext

AcademyEntities context = new AcademyEntities();

            string nativeSQLQuery =
                "SELECT * " +
                "FROM dbo.Employees " +
                "WHERE FirstName='{0}'";

            string name = "Guy";

            var emp = context.Departments.SqlQuery(nativeSQLQuery, name);

            foreach (var item in emp)
            {

            }
4

2 回答 2

1

您正在查询Employees表,但试图物化Department对象。

将您的呼叫更改为:

var emp = context.Employees.SqlQuery(nativeSQLQuery, name);

(并删除周围的引号{0}

于 2013-01-21T18:18:30.103 回答
1

您正在查询员工,因此您应该使用 context.Employees:

var emp = context.Employees.SqlQuery(nativeSQLQuery, name);
于 2013-01-21T18:18:48.270 回答