我正在建模音乐曲目和专辑,其中专辑有许多曲目,曲目只能在一张专辑上,并带有一个连接表来指定它在专辑列表中的位置。
这是我的模型:
public class Track
{
public int Id { get; set; }
public string Name { get; set; }
public int AlbumTrackId { get; set; }
public virtual AlbumTrack AlbumTrack { get; set; }
}
public class Album
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<AlbumTrack> AlbumTracks { get; set; }
}
public class AlbumTrack
{
public int AlbumId { get; set; }
public virtual Album Album { get; set; }
public int TrackId { get; set; }
public virtual Track Track { get; set; }
public int Position { get; set; }
}
和我的 EntityTypeConfiguration
public class AlbumTrackConfiguration : EntityTypeConfiguration<AlbumTrack>
{
public AlbumTrackConfiguration()
{
// AlbumTrack has a composite key
HasKey(at => new {at.AlbumId, at.TrackId});
// AlbumTrack has one Album, Albums have many AlbumTracks
HasRequired(at => at.Album)
.WithMany(a => a.AlbumTracks)
.HasForeignKey(at => at.AlbumId)
.WillCascadeOnDelete(true);
// AlbumTrack has one Track, Tracks have one AlbumTrack
HasRequired(at => at.Track)
.WithRequiredPrincipal(t=>t.AlbumTrack)
.WillCascadeOnDelete(true);
}
}
Albums 和 AlbumTracks 之间的一对多关系很好,但除了预期之外
[AlbumTrackId] [int] NOT NULL,
Code First 不断添加
[AlbumTrack_AlbumId] [int] NOT NULL,
[AlbumTrack_TrackId] [int] NOT NULL
到轨道表。
如何更好地对音轨到专辑音轨的关系进行建模,以便只有我指定的属性才能在 db 字段中进行翻译?
[是的,在我的世界里,一首歌只能存在于一张专辑中!]
谢谢。