How can I return a datareader when using Entity Framework 4?

白昼怎懂夜的黑 提交于 2019-12-21 03:31:06

问题


I want to define a database query using LINQ and my EntityFramework context but I don't want entities returned; I want a datareader!

How can I do this? This is for exporting rows to a CSV.

Cheers, Ian.


回答1:


This question is around EF 4, but for anyone else with EF 6 or higher you can use the AsStreaming() extension method.

http://msdn.microsoft.com/en-us/library/dn237204(v=vs.113).aspx




回答2:


If you need this you are more probably doing something unexpected. Simple iteration through materialized result of the query should be what you need - that is ORM way. If you don't like it use SqlCommand directly.

DbContext API is simplified and because of that it doesn't contain many features available in ObjectContext API. Accessing data reader is one of them. You can try to convert DbContext to ObjectContext and use the more complex API:

ObjectContext objContext = ((IObjectContextAdapter)dbContext).ObjectContext;
using (var connection = objContext.Connection as EntityConnection)
{
    // Create Entity SQL command querying conceptual model hidden behind your code-first mapping
    EntityCommand command = connection.CreateCommand();
    command.CommandText = "SELECT VALUE entity FROM ContextName.DbSetName AS entity";
    connection.Open();
    using (EntityDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
    {
        ...
    }
}

But pure ADO.NET way is much easier and faster because the former example still uses mapping of query to SQL query:

using (var connection = new SqlConnection(Database.Connection.ConnectionString))
{
    SqlCommand command = connection.CreateCommand();
    command.CommandText = "SELECT * FROM DbSetName";
    connection.Open();
    using(SqlDataReader reader = command.ExecuteReader())
    {

    }
}


来源:https://stackoverflow.com/questions/5925136/how-can-i-return-a-datareader-when-using-entity-framework-4

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