CommandBehavior.SequentialAccess


So why does this:


EntityDataReader reader  = command.ExecuteReader();

Throw an exception?


Well it is to-do with correctness and setting expectations.


First things first, this is what you should do:


EntityDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess);

But why?


What this does is explicitly open the reader the only way we currently support: sequentially. Which begs two questions:



  1. What does opening the reader sequentially mean?

  2. Why do we require that the user do so explicitly?

To answer the first question, imagine you have some code like this:


using (EntityDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
{


while (reader.Read()){


string surname = reader[1].ToString();


string firstname = reader[0].ToString();


Console.WriteLine(“{0},{1}”, firstname, surname);
}


}

If you try to run this you get this exception:


clip_image001


The exception tells the story. If you open a reader with SequentialAccess you must read the columns sequentially, you can’t read column 1 and then read column 0. You have to do it the other way around.


The question is why is SequentialAccess required for EntityDataReader?


Well in an EntityDataReader sometimes a Cell (the intersection of a row and column) actually holds another Reader too. Caching nested Readers you have read past is kind of tricky. So at least for now we don’t support non-sequential access.


Which brings us then to the second question.


Why do we force you to choose Sequential Access explicitly? Why don’t we just make it the default?


Here it basically boils down to consistency with other IDataReader implementations, every other implementation (at least that I know of) defaults to Non-Sequential Access, so we didn’t want to break that accepted pattern, even though all we support is Sequential Access.

Comments (4)

  1. Meta-Me says:

    Okay so about 5 posts back I promised: "…At this point we have an enumeration of all EntitySet s available.

  2. Okay so about 5 posts back I promised: "…At this point we have an enumeration of all EntitySet

  3. Blake J. says:

    in an EntityDataReader sometimes a Cell

    actually holds another Reader.

    The whole EF approach of "ever data value is a persistent entity" is really short-sighted and limiting.

    You need a way to execute a stored procedure, and return raw results, without cluttering up a logical entity model.

    Boy I really wish we’d used with nHibernate….

  4. Alex D James says:

    @Blake,

    We’ve added some surface here in EF 4 to help out.

    Checkout ObjectContext.ExecuteStoreQuery() and ExecuteStoreCommand();

    Hope this helps

    Alex