Entity framework 4.0 compiled query with Where() clause issue

Posted by Andrey Salnikov on Stack Overflow See other posts from Stack Overflow or by Andrey Salnikov
Published on 2010-05-18T08:41:15Z Indexed on 2010/05/18 8:51 UTC
Read the original article Hit count: 193

Hello,

I encountered with some strange behavior of System.Data.Objects.CompiledQuery.Compile function - here is my code for compile simple query:

private static readonly Func<DataContext, long, Product> productQuery = 
    CompiledQuery.Compile((DataContext ctx, long id) => 
        ctx.Entities.OfType<Data.Product>().Where(p => p.Id == id)
        .Select(p=>new Product{Id = p.Id}).SingleOrDefault()); 

where DataContext inherited from ObjectContext and Product is a projection of POCO Data.Product class.

My data context in first run contains Data.Product {Id == 1L} and in second Data.Product {Id == 2L}. First using of compilled query

productQuery(dataContext, 1L)

works perfect - in result I have Product {Id == 1L} but second run

productQuery(dataContext, 2L)

always returns null, instead of context in second run contains single product with id == 2L. If I remove Where clause I will get correct product (with id == 2L).

It seems that first id value caching while first run of productQuery, and therefore all further calls valid only when dataContext contains Data.Product {id==1L}. This issue can't be reproduced if I've used direct query instead of its precompiled version.

Also, all tests I've performed on test mdf base using SQL Server 2008 express and Visual studio 2010 final from my ASP.net application.

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about compiled-query