的DbContext原生SQL查询 [英] DBContext Native SQL Queries

查看:2257
本文介绍了的DbContext原生SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用与的DbContext 本机查询?如果我运行code,这给我的异常。为什么以及怎样做才能运行本地查询中使用时,的DbContext

  AcademyEntities背景=新AcademyEntities();            串nativeSQLQuery =
                SELECT *+
                FROM dbo.Employees+
                WHE​​RE名字='{0}';            字符串名称=人;            VAR EMP = context.Departments.SqlQuery(nativeSQLQuery,名);            的foreach(在EMP VAR项)
            {            }


解决方案

您要查询的员工表中,而是试图兑现部门的对象。

您的来电更改为:

  VAR EMP = context.Employees.SqlQuery(nativeSQLQuery,名);

(和删除引号轮 {0}

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)
            {

            }

解决方案

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

这篇关于的DbContext原生SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆