mrJack
mrJack

Reputation: 1011

EntityDataReader to ToList()

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?

Upvotes: 1

Views: 2897

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

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.

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))
        {
            var s = from d in rdr.OfType<Book>().AsEnumerable()
                    select d;
            return (s.ToList());
        }
    }
}

s.ToList().Count returns 0 because rdr.OfType<Book> is always empty collection. EntitDataReader doesn't materialize entities - it is just wrapper about database related DataReader 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 with ObjectContext you don't need EntityCommand and EntityDataReader at all.

Upvotes: 2

Related Questions