当我尝试在 EF Core 中设置多对多关系并在 Swagger 中捕获结果时遇到问题。
public class Book
{
[Key]
public int BookId { get; set; }
public string? BookName { get; set; }
}
public class Publisher
{
[Key]
public int PublisherId { get; set; }
public string? PublisherName { get; set; }
public ICollection<BookPublisher? BookPublishers { get; set; }
}
public class BookPublisher
{
[Key]
public int BookPublisherId { get; set; }
public int BookId { get; set; }
public int PublisherId { get; set; }
public Book? Book { get; set; }
}
在
DbContext
中,我有:
DbSet<Publisher>? Publishers { get; set; }
DbSet<BookPublisher>? BookPublishers { get; set; }
DbSet<Book>? Books { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Publisher>().ToTable("TAB_Publisher", "dbo");
builder.Entity<BookPublisher>().ToTable("TAB_BookPublisher", "dbo");
builder.Entity<Book>().ToTable("TAB_Book", "dbo");
}
public List<Publisher>? GetPublishers()
{
if (Publishers != null)
return Publishers
.Include(s => s.BookPublishers).ThenInclude(s => s.Book)
.ToList<Publisher>();
else
return null;
}
当我在 Swagger 中调用我的方法
GetPublishers
时,我得到了我想要的:
[
{
"PublisherId": 1,
"PublisherName": "GrpPdcTestTGO",
"BookPublisher": [
{
"BookPublisherId": 1,
"BookId": 1,
"PublisherId": 1,
"Book": {
"BookId": 1,
"BookName": "TEST1",
}
},
{
"BookPublisherId": 2,
"BookId": 2,
"PublisherId": 1,
"Book": {
"BookId": 2,
"BookName": "TEST2",
}
},
]
}
]
怎样才能得到与书本相同的结果?一本书可以有多个出版商。我必须建立什么样的关系?
你是对的,我有一个循环引用,但这很正常,因为我的 CDM 是这样的: 在此输入图片描述
我将有 2 个方法 GetPublishers 和 GetBooks。 当我得到 GetPublishers 的结果时,我想要这个
[
{
"PublisherId": 1,
"PublisherName": "NamePublisher1",
"BookPublisher": [
{
"BookPublisherId": 1,
"BookId": 1,
"PublisherId": 1,
"Book": {
"BookId": 1,
"BookName": "TEST1",
}
},
{
"BookPublisherId": 2,
"BookId": 2,
"PublisherId": 1,
"Book": {
"BookId": 2,
"BookName": "TEST2",
}
},
]
}
]
当我想要 GetBooks 的结果时,结果必须是这样的
[
{
"BookId": 1,
"BookName": "TEST1",
"BookPublisher": [
{
"BookPublisherId": 1,
"BookId": 1,
"PublisherId": 1,
"Publisher": {
"PublisherId": 1,
"PublisherName": "NamePublisher1",
}
}
]
},
{
"BookId": 2,
"BookName": "TEST2",
"BookPublisher": [
{
"BookPublisherId": 2,
"BookId": 2,
"PublisherId": 1,
"Publisher": {
"PublisherId": 1,
"PublisherName": "NamePublisher1",
}
}
]
}
]
所以我之前的类定义都可以,并且在方法“OnModelCreating”上我没有放置关系。