8

I'm getting a "Code supposed to be unreachable" error when executing the following Linq to Sql statement. I'm using EF 6.1.3. I think this is a known bug related to filtering a navigation property. It seems like it might be fixed in EF7 but I don't see anything related to this in the EF 6.2 release notes nor the EF6 open items on GitHub so I guess I'm looking for a work around, maybe a different way of writing my Linq statement.

Ultimately, I am applying the same where clause (AccountSecurity) in multiple places (also based on passing a user key parameter) so I thought I'd be able to turn it into a function that generates the Expression to use in the where clause in my Linq to Sql statement.

    public List<Company> GetCompanyList(int p_UserKey, MemberType p_MemberType)
    {
        var qry = from cs in this.DbContext.CompanySet
                  .Where(c => c.Accounts.AsQueryable().Any(this.AccountSecurity(p_UserKey)))
                  select cs;
        return qry.ToList();
    }

    private Expression<Func<Account, bool>> AccountSecurity(int p_UserKey)
    {
        return (ac => ac.UserAccounts.Any(ua => ua.UserKey == p_UserKey));
    }
SteveB
  • 233
  • 3
  • 12

1 Answers1

7

As a workaround, you can capture the method call into variable outside the query expression tree and use that variable inside:

var accountFilter = this.AccountSecurity(p_UserKey);
var qry = from cs in this.DbContext.CompanySet
          .Where(c => c.Accounts.AsQueryable().Any(accountFilter))
          select cs;
return qry.ToList();
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • This doesn't fix my problem. Same error. Thanks for contributing. – SteveB Nov 16 '17 at 14:22
  • EF being EF. This did the trick for me, but I used the expression inside a Where and inside a Select, so I had to replace in both places for it to work. – Edgar Froes Jan 03 '19 at 18:50
  • Surprisingly for me using first a variable did the trick! Thanks a lot! – ppenchev Apr 10 '19 at 21:18
  • Thank you, it helps for Any method, but for Where is not needed. Strange effect. – VikciaR May 04 '20 at 12:29
  • @VikciaR I don't think the operator (`Where`, `Any` etc.) matters, but whether it is part of top level operator or lambda expression. It's not so strange when you realize that in lambda expression (`Expression>`) like `c => c.Accounts.AsQueryable().Any(this.AccountSecurity(p_UserKey))`, nothing in the body (after `=>`) is actually executed. And `IQueryable` translators usually do not process unknown methods. – Ivan Stoev May 04 '20 at 12:52