How can i return a dataReader using Entity Framework 6.1?

混江龙づ霸主 提交于 2019-12-22 09:56:46

问题


Exactly as the question asks. I am using entity framework for most of my code, but i also need to execute and return a count or columns from a sql table that is not within my entity framework context.


回答1:


You can run a raw query using Entity Framework, for example:

using (var context = new BloggingContext()) 
{ 
    var blogNames = context.Database.SqlQuery<string>( 
                       "SELECT Name FROM dbo.Blogs").ToList(); 
}

If you want to return a more complex type, you can define your own class and use that instead. As long as the properties match the names of the columns you select, it will work. So lets make a class:

public class MyClass
{
    public int Id { get; set; }
    public string UserName { get; set; }
}

And use it:

List<MyClass> result = ctx
    .Database.SqlQuery<MyClass>("SELECT Id, UserName FROM dbo.Users")
    .ToList();



回答2:


The whole point of an IDataReader is to Cursor through the data as it is being returned over the wire (exempli gratia TCP/IP) and thus not incur the overhead of stuffing it all into memory. If you're dealing with millions of rows, then reading everything into memory is a bad idea. If that is the case, then grab the underlying connection string from EF API and utilize ADO.NET. There's better better Aysnc support there as well.



来源:https://stackoverflow.com/questions/31336022/how-can-i-return-a-datareader-using-entity-framework-6-1

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