从多对多关系查询 table

Query from a many to many relationship table

我有两个 tables DocumentsGroup,如下所示。我首先使用代码加入了两个 table 创建一个 DocumentsGroup

文件 Table:

public class Documents
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<Group> Groups { get; set; 
}

群组Table:

public class Group
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<Documents> Documents { get; set; }
}

这是文档组 table。这是路口 table,它没有模型,只是展示它的外观。

{
    public int DocumentsId { get; set; }

    public int GroupsId{ get; set; }
}

我正在尝试从连接点 table 获取属于一个组的所有文档。我有组 ID,所以我正在尝试获取属于该 ID 的所有文档,如下所示:

int groupId = 4;
var documents = _database.Groups.Where(d => d.Id == groupId).Include(i => i.Documents).ToList();

我试过了,但没有得到属于该组的所有文档。有什么地方做错了吗?

您编写的查询将 return 一组结果集,而不是文档。如果“组”table 的“Id”列是唯一的,则应将其写为:

var group = dbContext.Groups.Include(g => g.Documents).FirstOrDefault(g => g.Id == 4); //Given group id is 4
if (group != null) { 
      var documents = group.Documents.ToList(); // Here you should get the desired Documents, given that the the tables are correctly configured 
}

尝试通过映射到达文档 table

            int groupId = 4;
            var documents = _database.DocumentsGroup
            .Where(x => x.GroupId == groupId)
            .Include(x => x.Documents)
            .Select(x => new Documents
            {
                Id = x.Documents.Id,
                // add all props you need
            })
            .ToList();

但是如果您没有映射 table 只需创建它或者您可以尝试:

            int groupId = 4;
            var documents = _database.Groups
            .Include(x => x.Documents)
            .Where(x => x.Id == groupId )
            .ToList();

使用以下查询:

int groupId = 4;

var query = 
    from g in _database.Groups
    from d in g.Documents
    where g.Id == groupId
    select d;

var documents = query.ToList();

或通过方法链语法:

int groupId = 4;

var documents = _database.Groups
    .Where(g => g.Id == groupId)
    .SelectMany(g => g.Documents)
    .ToList();