我想使用 LINQ 和我的 EntityFramework 上下文定义一个数据库查询,但我不想返回实体;我想要一个数据阅读器!
我怎样才能做到这一点?这是用于将行导出到 CSV。
干杯,伊恩。
最佳答案
如果你需要这个,你更有可能做一些意想不到的事情。通过查询的物化结果进行简单迭代应该是您所需要的 - 这就是 ORM 方式。如果您不喜欢它,请使用 SqlCommand
直接地。
DbContext API 被简化,因此它不包含 ObjectContext API 中可用的许多功能。访问数据阅读器就是其中之一。您可以尝试转换 DbContext
至 ObjectContext
并使用更复杂的 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))
{
...
}
}
但是纯 ADO.NET 方式更容易和更快,因为前一个示例仍然使用查询到 SQL 查询的映射:
using (var connection = new SqlConnection(Database.Connection.ConnectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM DbSetName";
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
}
}
关于entity-framework - 使用 Entity Framework 4 时如何返回数据读取器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5925136/