使用 Linq 查询的帮助

4
我刚接触LINQ,需要查询的帮助。
我需要从(tblResources)中获取所有属于匿名公共ResourceGroups(tblResourceGroups)的资源。此外,我还需要所有属于currentUser所属的ResourceGroups资源
如果currentUser没有登录(currentUser == null),则只应返回属于AnonymousPublic ResourceGroups资源
注意:我的数据模型不包含tblResourceAccess实体。我不知道为什么在创建模型时未添加此实体。
        string currentUser = IdentityHelper.GetUserIdFromRequest(Context.Request);

        var result = from r in DbContext.Resources                                                                           
                     where r.Active == true // && r.ResourceGroups?????                         
                     select new
                     {                                                          
                         ResourceTypeName = r.ResourceType.Name,
                         Name = r.Name,
                         Version = r.Version,
                         Description = r.Description,
                         Path = r.Path,
                         Active = r.Active
                     };

Entity Data Models

Database Tables


1
你的第一步应该是重新创建你的模型,这样Access表就可以获取数据对象了。 - krillgar
2个回答

1
"

tblResourceAccess被EF抽象化了,ResourceGroups属性被添加到Resource表中以提供功能。利用这个关系,我们可以拼接出以下查询:

"
from r in DBContext.Resources.ToList()
where (currentUser == null 
        && ("anonymous,public").Contains(
            r.ResourceGroups.Name.ToLower()))
    || (currentUser != null)
select new
    {                                                          
        ResourceTypeName = r.ResourceType.Name,
        Name = r.Name,
        Version = r.Version,
        Description = r.Description,
        Path = r.Path,
        Active = r.Active
    };

谢谢你的帮助!有任何想法为什么会出现“当前上下文中不存在名称'r'”的错误?请包含(r.ResourceGroups)。 - Sean
你可以安全地删除Include,我只是为了完整性而放置它。 - The Sharp Ninja
移除Include后,我得到了这个错误。错误2:'System.Collections.Generic.ICollection<Web.Models.ResourceGroup>'不包含'ResourceGroup'的定义,也没有接受类型为'System.Collections.Generic.ICollection<Web.Models.ResourceGroup>'的第一个参数的扩展方法'ResourceGroup'可以找到(您是否缺少使用指令或程序集引用?)C:\Eagle\Web\Web\Support\Downloads.aspx.cs 51 50 Web - Sean
"ResourceGroup" 还是 "ResourceGroups"? 你漏掉了 "s" 吗? - alsafoo
r.ResourceGroups.Name.ToLower - 错误1:'System.Collections.Generic.ICollection<Web.Models.ResourceGroup>'不包含“Name”的定义,也没有接受类型为'System.Collections.Generic.ICollection<Web.Models.ResourceGroup>'的第一个参数的扩展方法“Name”可以找到(是否缺少使用指令或程序集引用?)C:\Eagle\Web\Web\Support\Downloads.aspx.cs 51行55列 Web - Sean

1

终于,在经过很多尝试和错误之后!我不确定这是实现此查询的性能最佳方式,但它有效。

感谢您的帮助@The Sharp Ninja

string currentUser = IdentityExtensions.GetUserId(HttpContext.Current.User.Identity);

var resources = from r in DbContext.Resources                            
                where r.ResourceGroups.Any(
                      rg => rg.Name == "Anonymous" || 
                      rg.Name == "Public" || 
                      rg.ResourceUserGroups.Any(ug => ug.UserID == currentUser))
                select r;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接