DBContext Native SQL Queries

一世执手 提交于 2019-12-11 18:32:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!