Given LINQ to Entities does not support “Custom methods” how do you stay DRY?

前端 未结 2 640
旧巷少年郎
旧巷少年郎 2020-12-17 21:08

I have run into this problem:

Custom Methods & Extension Methods cannot be translated into a store expression

Basically I have some complicated LINQ quer

相关标签:
2条回答
  • 2020-12-17 21:50

    Two ways:

    1. Methods which return expressions can be used
    2. Separate the queryable and enumerable bits

    For #1, consider:

    public Expression<Func<Foo, bool>> WhereCreatorIsAdministrator()
    {
        return f => f.Creator.UserName.Equals("Administrator", StringComparison.OrdinalIgnoreCase);
    }
    
    public void DoStuff()
    {
        var exp = WhereCreatorIsAdministrator();
        using (var c = new MyEntities())
        {
            var q = c.Foos.Where(exp); // supported in L2E
            // do stuff
        }
     }
    

    For an example of number 2, read this article: How to compose L2O and L2E queries. Consider the example given there:

    var partialFilter = from p in ctx.People
                        where p.Address.City == “Sammamish”
                        select p;
    
    var possibleBuyers = from p in partiallyFilter.AsEnumerable()
                         where InMarketForAHouse(p);
                         select p;
    

    This might be less efficient, or it might be fine. It depends on what you're doing. It's usually fine for projections, often not OK for restrictions.

    Update Just saw an even better explanation of option #1 from Damien Guard.

    0 讨论(0)
  • 2020-12-17 21:52

    EF can't compose a query out of a LINQ expression that includes a method. EF needs literal values to compose the SQL.

    You will have to make do with "common" queries that return a superset of the Entities you need for a given case, then use extension methods and LINQ to narrow down the return set once it has been returned from the database.

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