从SQL查询执行实体框架匿名类型的搜索结果 [英] Anonymous type result from sql query execution entity framework

查看:346
本文介绍了从SQL查询执行实体框架匿名类型的搜索结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架5.0的.NET Framework 4.0的代码第一种方法。现在我知道,我可以通过以下运行的实体框架原始的SQL

I am using entity framework 5.0 with .net framework 4.0 code first approach. Now i know that i can run raw sql in entity framework by following

var students = Context.Database.SqlQuery<Student>("select * from student").ToList();



它的工作完美,但我想要的是返回匿名结果。比如我想从学生表中只有特定的列像下面

It's working perfectly but what I want is return anonymous results. For example I want only specific columns from student table like following

var students = Context.Database.SqlQuery<Student>("select FirstName from student").ToList();



这是行不通的。它提供了异常

It is not working. it gives exception

数据读取器是指定的MyApp.DataContext.Student不兼容。该类型的成员,StudentId,不具有相同名称的数据读取相应的列。

The data reader is incompatible with the specified 'MyApp.DataContext.Student'. A member of the type, 'StudentId', does not have a corresponding column in the data reader with the same name.

所以我试图动态键入

var students = Context.Database.SqlQuery<dynamic>("select FirstName from student").ToList();



它也不能正常工作,它返回一个空的对象。没有在它的数据。

it is also not working, it returns an empty object. No data available in it.

有没有办法从一个动态的SQL查询中获取匿名类型的结果?

Is there any way to get anonymous type result from a dynamic SQL query?

推荐答案

您可以尝试这里的代码,然后找到stankovski的实现:
http://www.codeproject.com/Articles/206416/Use-dynamic-type-in​​-Entity-Framework-SqlQuery

You can try the code from here, scroll down and find the implement of stankovski: http://www.codeproject.com/Articles/206416/Use-dynamic-type-in-Entity-Framework-SqlQuery

中的代码复制到一个静态类后,你可以调用这个函数来得到你想要什么:

After copying the code into a static class, you can call this function to get what you want:

var students = Context.Database.DynamicSqlQuery("select FirstName from student").ToList()

这篇关于从SQL查询执行实体框架匿名类型的搜索结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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