c# - 如何使用 linq 加入多对多关系

标签 c# linq concatenation inner-join

我想问一下如何查询来选择每本书的类型,我尝试了很多方法,但都失败了。

书:

public class Book
{
    public int Id { get; set; }
    [StringLength(100)]
    public string Title { get; set; }
    public virtual ICollection<Genre> Genres { get; set; }
    public virtual Author Author { get; set; }
}

类型:

public class Genre
{
    public int Id { get; set; }
    [StringLength(32)]
    public string Name { get; set; }
    public virtual ICollection<Book> Books { get; set; }
}

作者:

public class Author
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public virtual ICollection<Book> Books { get; set; }
}

我尝试过的: (我用“?”标记了我不能再做的地方)

from book in Books
join author in Authors on book.Author.Id equals author.Id
??join Genre ??
select new {book, author, ?list genres}

最佳答案

使用 SelectMany :

    class Program
    {
         static void Main(string[] args)
        {
            Context db = new Context();

            var results = db.Book.SelectMany(x => x.Genres.Select(y => new
            {
                id = x.Id,
                title = x.Title,
                authorId = x.Author.Id,
                authorName = x.Author.FullName,
                genreId = y.Id,
                genreName = y.Name
            })).ToList();
 

        }
    }
    public class Context
    {
        public List<Book> Book { get; set; }
        public List<Genre> Genre { get; set; }
        public List<Author> Author { get; set; }
    }
    public class Book
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public virtual ICollection<Genre> Genres { get; set; }
        public virtual Author Author { get; set; }
    }
    public class Genre
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Book> Books { get; set; }
    }
    public class Author
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public virtual ICollection<Book> Books { get; set; }
    }
 

关于c# - 如何使用 linq 加入多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67402843/

相关文章:

c# - 如何使用 RegEx 提取 Skype 帐户

c# - Linq-To-Sql 查询中的模糊调用

c# - 将 IQueryable<T> 或 LINQ 查询转换为唯一字符串

c# - 在 Entity Framework 中联合或连接自定义数据

c++ - "Variable"变量名 C++

java - 在编写构造函数时将属性串联到即时变量中

C# Regex 将 aabbccddeeff 匹配为两个 aabbcc 和 ddeeff 集

c# - log4net可以输出Json吗?

c# - 如何使用 LINQ 仅返回列的第一个字符在某个范围内的行?

c# - 如何在 Visual Studio 2010 Express 中引用 system.drawing?