System.Core错误:“代码应该无法访问”使用C#Entity Framework和Linq with Expression

时间:2017-11-01 19:15:28

标签: c# entity-framework entity-framework-6 linq-to-entities linq-expressions

执行以下Linq to Sql语句时,我收到“代码无法访问”错误。我正在使用EF 6.1.3。我认为这是一个与过滤导航属性相关的已知错误。好像它可能在EF7中修复但我在EF 6.2发行说明中没有看到与此相关的任何内容,也没有看到GitHub上的EF6打开项目,所以我想我正在寻找一种解决方法,也许是一种不同的写作方式我的Linq声明。

最终,我在多个地方应用相同的where子句(AccountSecurity)(也基于传递用户键参数),所以我认为我能够将其转换为生成要在我的Linq to Sql语句中的where子句。

    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));
    }

1 个答案:

答案 0 :(得分:5)

作为一种变通方法,您可以将方法调用捕获到查询表达式树之外的变量中,并在其中使用该变量:

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();