How to wrap Entity Framework to intercept the LINQ expression just before execution?

后端 未结 3 500
深忆病人
深忆病人 2020-12-02 07:03

I want to rewrite certain parts of the LINQ expression just before execution. And I\'m having problems injecting my rewriter in the correct place (at all actually).

3条回答
  •  天命终不由人
    2020-12-02 07:24

    Just wanted to add to Arthur's example.

    As Arthur warned there is a bug in his GetObjectQuery() method.

    It creates the base Query using typeof(T).Name as the name of the EntitySet.

    The EntitySet name is quite distinct from the type name.

    If you are using EF 4 you should do this:

    public override IQueryable GetObjectQuery()
    {
        if (!_table.ContainsKey(type))
        {
            _table[type] = new QueryTranslator(
                _ctx.CreateObjectSet();
        }
    
        return (IQueryable)_table[type];
    }
    

    Which works so long as you don't have Multiple Entity Sets per Type (MEST) which is very rare.

    If you are using 3.5 you can use the code in my Tip 13 to get the EntitySet name and feed it in like this:

    public override IQueryable GetObjectQuery()
    {
        if (!_table.ContainsKey(type))
        {
            _table[type] = new QueryTranslator(
                _ctx.CreateQuery("[" + GetEntitySetName() + "]"));
    
        } 
        return (IQueryable)_table[type];
    }
    

    Hope this helps

    Alex

    Entity Framework Tips

提交回复
热议问题