我想问一下如何查询来选择每本书的类型,我尝试了很多方法,但都失败了。
书:
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/