问题
How to use native queries with DBContext
? If I run the code, this give me exception. Why and what to do to run native query when using 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)
{
}
回答1:
You're querying the Employees
table, but trying to materialize Department
objects.
Change your call to:
var emp = context.Employees.SqlQuery(nativeSQLQuery, name);
( and remove the quotes round the {0}
)
回答2:
You are querying Employees, so you should use context.Employees:
var emp = context.Employees.SqlQuery(nativeSQLQuery, name);
来源:https://stackoverflow.com/questions/14444684/dbcontext-native-sql-queries