Entity Framework Compiled Query

后端 未结 2 1081
醉酒成梦
醉酒成梦 2020-12-06 08:35

How do I write this Entity Framework LINQ Query as a Compiled Query?

var context = new SlxDbContext();
var userSet = context.Set();
User user = u         


        
相关标签:
2条回答
  • 2020-12-06 08:42

    Unfortunately the version of EF you are using (code first), does not support compiled queries.

    Please correct me if I'm wrong.

    Some links:

    How do I precompile an Entity Framework Code-First Query?

    EF Code First DbContext and Compiled Queries

    http://blogs.msdn.com/b/adonet/archive/2011/03/02/ef-4-1-is-coming-dbcontext-api-amp-code-first-rtw.aspx

    UPDATE:

    Here is a sample for compiled queries, but I think it's not going to work with Code First:

    public static Shop CompiledGetShopById(Guid shopId)
    {
        using (DataContext dtx = new DataContext(ConfigProvider.ConnectionString)) {
            return Compiled_GetById.Invoke(dtx, shopId);
        }
    
    }
    
    private static Func<DataContext, Guid, Shop> Compiled_GetById = 
        Objects.CompiledQuery.Compile<DataContext, Guid, Shop>(
            (DataContext db, Guid shopId) => 
                (from item in db.Shops where item.ShopId == shopId)
                .FirstOrDefault()
        );
    
    0 讨论(0)
  • There's no way to use CompiledQuery when you're using the DbContext API; CompiledQuery works only with ObjectContext. If you're using Code First, you're most likely using the DbContext API. And Microsoft recommends that you use the DbContext API in new projects even if you'll be working with Database First or Model First models.

    But if you use EF5, it brings auto-compiled queries, which work very differently than CompiledQuery. Instead of your writing code to compile each query and then invoking each as needed, EF5 caches the generated SQL for you as a background process, then searches the cache for already compiled queries when you execute any query.

    See:

    http://blogs.msdn.com/b/adonet/archive/2012/02/14/sneak-preview-entity-framework-5-0-performance-improvements.aspx

    and

    http://www.devproconnections.com/article/entity-framework/entity-framework-5-143875

    0 讨论(0)
提交回复
热议问题