使用 .NET ASPNET WebApi。
我有一个简单的模型。一首歌和一个 Artisk,一首歌可以有多个艺术家,一个艺术家可以与多首歌曲相关 - 多对多关系。
public class Artist
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? Born { get; set; }
}
public class Song
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime ReleaseDate { get; set; }
public Genre? Genre { get; set; }
public ICollection<SongArtist> Artists { get; set; }
}
public class SongArtist
{
public int Id { get; set; }
public Song Song { get; set; }
public Artist Artist { get; set; }
}
我正在构建一个 API 操作模型,我想知道如何处理 POST 的最佳方法。显然,我在创建歌曲时需要添加多个艺术家。我可以看到 3 种可能的解决方案:
我正在使用 DTO 对象,显示我刚刚在 ArtistDTO 上添加了一个列表。像这样的东西:
public class SongDto
{
public int Id { get; set; }
[Required]
[MinLength(2)]
public string Name { get; set; }
[Required]
public DateTime ReleaseDate { get; set; }
public ICollection<ArtistDto> Artists { get; set; }
}
然后在body中提供它。
从查询中读取 ID 数组
单独的端点来添加和删除歌曲上的艺术家?
尝试查找有关该主题的信息,但没有运气。
与 EF 建立多对多关系有点棘手。这需要对现有的 DTO 进行一些更改,就像
实体类
public class Song
{
public int SongId { get; set; }
public string Name { get; set; }
public DateTime ReleaseDate { get; set; }
public Genre? Genre { get; set; }
public List<Artist> Artists { get; } = [];
}
public class Artist
{
public int ArtistId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? Born { get; set; }
public List<Song> Songs { get; } = [];
}
public class SongArtist
{
public int SongId { get; set; }
public Song Song { get; set; }
public int ArtistId { get; set; }
public Artist Artist { get; set; }
}
然后要使 EF 理解多对多关系,您可以使用 OnModelCreating 重写方法,如下所示
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Song>()
.HasMany(e => e.Artists)
.WithMany(e => e.Songs)
.UsingEntity<SongArtist>();
}
我建议仔细阅读带有命名连接表的多对多。此 MSDN 链接将提供建立多对多关系的各种方法