EntityDataReader 到 ToList()
我的代码:
public List<Book> GetBook(string Field, object Value)
{
using (EntityConnection conn = new EntityConnection("name=Entities"))
{
conn.Open();
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select VALUE b FROM Entities.Book as b where Cast(b." + Field + " as Edm.String) like '%" + Value.ToString() + "%'";
// Execute the command.
using (EntityDataReader rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
conn.Close();
var s = from d in rdr.OfType<Book>().AsEnumerable()
select d;
return (s.ToList());
}
}
}
return (null);
}
为什么结果总是空???
正确的代码是什么?
my code :
public List<Book> GetBook(string Field, object Value)
{
using (EntityConnection conn = new EntityConnection("name=Entities"))
{
conn.Open();
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select VALUE b FROM Entities.Book as b where Cast(b." + Field + " as Edm.String) like '%" + Value.ToString() + "%'";
// Execute the command.
using (EntityDataReader rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
conn.Close();
var s = from d in rdr.OfType<Book>().AsEnumerable()
select d;
return (s.ToList());
}
}
}
return (null);
}
why The result is always empty???
What is the correct code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么在开始阅读阅读器之前要关闭连接? Reader 就像游标 - 当您打开它时,它不会将所有结果缓冲到内存中,而是增量加载它们,以便您可以在读取任何结果之前轻松终止连接(以及读取功能)。您不必显式关闭连接 - 这是
using
块的责任。您还可以使用 SQL 探查器来验证它是否确实构建了您期望的查询。
s.ToList().Count
返回 0,因为rdr.OfType
始终为空集合。EntitDataReader
不会具体化实体 - 它只是与数据库相关的DataReader
的包装器,并且以相同的方式工作。您必须读取列并将其填充到实体的属性中。如果您不想这样做,您可以使用
objectContext.Translate
方法,但一旦开始使用ObjectContext
,您就不需要EntityCommand
> 和 EntityDataReader 。Why are you closing connection before you started to read from the reader? Reader is like cursor - it doesn't buffer all results to memory when you open it but it loads them incrementally so you could easily terminate connection (and reading functionality as well) before you read any result. You don't have to close the connection explicitly - that is responsibility of
using
block.You can also use SQL profiler to validate the it really builds the query you expect.
s.ToList().Count
returns 0 becauserdr.OfType<Book>
is always empty collection.EntitDataReader
doesn't materialize entities - it is just wrapper about database relatedDataReader
and it works in the same way. You must read columns and fill them to properties of your entity.If you don't want to do it you can use
objectContext.Translate
method but once you start to work withObjectContext
you don't needEntityCommand
andEntityDataReader
at all.