简体   繁体   English

Linq c# 查询加入两个多对多关系

[英]Linq c# query to join two many to many relationship

here i have a group containing many users and assets ,i want list of assets linked to a single user.这里我有一个包含许多用户和资产的组,我想要链接到单个用户的资产列表。 What is the best way of using linq.使用 linq 的最佳方式是什么?

 public class Asset
    { 
        public Guid Id { get; set; }
        public virtual ICollection<GroupToAssets> GroupToAssets { get; set; }
    }

 public class User: IdentityUser
    {
       public virtual ICollection<GroupToUsers> GroupToUsers { get; set; }
    }

 public class GroupToAssets
    {     
        public Guid GroupId { get; set; }
        public virtual Group Group { get; set; }
        public Guid AssetId { get; set; }
        public virtual Asset  Asset { get; set; }
    }

 public class GroupToUsers
    {   
        public Guid GroupId { get; set; }
        public virtual  Group Group { get; set; }
        public string UserId { get; set; }
        public virtual User User { get; set; }
    }

I think the following linq satisfy my case don't know if there is a better method我认为以下linq满足我的情况不知道是否有更好的方法

   var Groups =
 await _Context.Groups.Where(x => x.GroupToUsers.Any(d => d.UserId == UserId && d.GroupId == x.Id)).ToListAsync();
    var assets =
 await _Context.GroupToAssets.Where(x => Groups.Contains(x.Group)).Select(x => new { x.Asset }).Distinct().ToListAsync();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM