简体   繁体   中英

Does ObjectContext.ExecuteStoreQuery iterate over the result set?

I am using ObjectContext.ExecuteStoreQuery to return a list of entities, about 30K.

I need to improve performance so I will be "selecting" 4 properties that I really need, instead of the total 20 properties.

I could create a DTO with these 4 properties and pass it to ObjectContext.ExecuteStoreQuery, but I would prefer to use a DataReader, iterate over the 30K, and build my list.

I tried both options and it "seems" they take the same time (did not measure it). My question is -does ObjectContext.ExecuteStoreQuery iterate over the result set, as I am doing manually with a DataReader?

I found this in MSDN, but does not really answer my question. Thank you.

Calling the ExecuteStoreQuery method is equivalent to calling the ExecuteReader method of the DbCommand class, only ExecuteStoreQuery returns entities and the ExecuteReader returns property values in the DbDataReader.

If you mean, does it hit the database on each iteration, then (going by the documentation) no it will load the entire resultset into your entity. Once loaded, it will iterate through the stored data in memory, though

ExecuteStoreQuery returns a System.Data.Objects.ObjectResult and it query directly the database using TSQL, you won't have a stream but just a collection of all the objects queried.

http://blogs.msdn.com/b/alexj/archive/2009/11/07/tip-41-how-to-execute-t-sql-directly-against-the-database.aspx

If I understand correctly this is not what you want.

If you want to query data in some sort of way similar to a classic ADO.NET DataReader you should query directly the EntityClient , it is different from using Linq To Entities or ESQL because you do not pass through the ObjectContext, and the query will not materializes any object!

using (EntityConnection conn = new EntityConnection("name=SampleEntities"))
{
    conn.Open();
    EntityCommand cmd = conn.CreateCommand();
    cmd.CommandText = "SELECT VALUE c FROM SampleEntities.Contacts AS c WHERE c.FirstName='Robert'";
    using (EntityDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection))
    {
        while (rdr.Read())
        {
            var firstname = rdr.GetString(1);
            var lastname = rdr.GetString(2);
        }
    }
    conn.Close();
}

It is helpful if you need just to query some read-only data you need to display in some way, it is no different from creating any other provider command and setting its CommandText, but The CommandText here is the Entity SQL expression and you obviously query the EDM that i think it is why you are using EF.

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM