无法识别具有内联函数的LINQ to Entities

时间:2015-10-30 17:45:56

标签: c# entity-framework linq

我在LINQ查询中收到以下错误:

    public IQueryable<Group> GetGroups()
    {
        string userEID = HttpContext.Current.Request.LogonUserIdentity.Name.ToUpper();
        return db.Groups.Where(sg => sg.GroupActive == true && userEID == getGroupOwner(sg.GroupSecurity)).OrderBy(g => g.GroupName);
    }

    private string getGroupOwner(string GName)
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, GName);
        System.DirectoryServices.DirectoryEntry de = (System.DirectoryServices.DirectoryEntry)group.GetUnderlyingObject();
        var owner = de.Properties["managedBy"];
        return owner.Value.ToString().ToUpper();
    }

我发现这个问题看起来很相似:LINQ to Entities does not recognize the method

我知道问题是LINQ需要将语句转换为SQL并且函数不能包含在内但我正在努力弄清楚如何重写它。

以下是我的两个功能:

public IQueryable<Group> GetGroups()
{
    string userEID = HttpContext.Current.Request.LogonUserIdentity.Name.ToUpper();
var rs = db.Groups.Where(sg => sg.GroupActive == true).OrderBy(g => g.GroupName);
        foreach (var gname in rs)
        {
                var groupOwner = getGroupOwner(gname.GroupSecurity);
                if (groupOwner != userEID)
                {
                    //I think I need to remove gname from rs here - What is the proper syntax?
                }
        }
        return rs;
}

任何帮助都会非常感激!提前谢谢。

编辑#1:

感谢评论@DevilSuichiro。这是我的第一次修订,我认为更接近。这是正确的轨道吗?删除项目的语法是什么。

{{1}}

1 个答案:

答案 0 :(得分:0)

当您枚举IEnumerable中的项目时,您无法从IEnumerable中删除会产生错误的项目。但是,您可以选择所需的所有元素并返回这些元素。这样的事情。

public IQueryable<Group> GetGroups()
{
    string userEID = HttpContext.Current.Request.LogonUserIdentity.Name.ToUpper();
    var rs = db.Groups.Where(sg => sg.GroupActive == true).OrderBy(g => g.GroupName);
    var toReturn = new List<Group>();
    foreach (var gname in rs)
    {
            var groupOwner = getGroupOwner(gname.GroupSecurity);
            if (groupOwner == userEID)
            {
                toReturn.Add(gname);
            }
    }
    return toReturn.AsQueryable<Group>();
}