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?
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
usingblock.You can also use SQL profiler to validate the it really builds the query you expect.
s.ToList().Countreturns 0 becauserdr.OfType<Book>is always empty collection.EntitDataReaderdoesn’t materialize entities – it is just wrapper about database relatedDataReaderand 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.Translatemethod but once you start to work withObjectContextyou don’t needEntityCommandandEntityDataReaderat all.