我正在使用 MVC 4 和 Entity Framework 5 Code First。
我有以下实体:
public class File
{
public string Album { get; set; }
public string Genre { get; set; }
}
public class Genre
{
public string GenreId { get; set; }
public virtual List<Album> Albums { get; set; }
}
public class Album
{
public string AlbumId { get; set; }
}
我尝试将它们添加到数据库中:
private readonly List<File> _files = new List<File>();
var genres = _files
.Select(x => new Genre { GenreId = x.Genre })
.GroupBy(x => x.GenreId)
.Select(x => x.First())
.ToList();
foreach (var genre in genres)
{
var genreId = genre.GenreId;
var albums = _files
.Where(x => x.Genre == genreId)
.Select(x => new Album { AlbumId = x.Album })
.GroupBy(x => x.AlbumId)
.Select(x => x.First())
.ToList();
genre.Albums = albums;
_unitOfWork.GenreRepository.Insert(genre);
}
我收到以下错误:
Violation of PRIMARY KEY constraint 'PK_dbo.Albums'. Cannot insert duplicate key in object 'dbo.Albums'. The duplicate key value is (Ooz).
该语句已终止。
我尝试添加的数据如下所示:
--Tribal
----Ooz
--Goa Trance
----Ooz
----Transient Dawn
--Progressive Trance
----Ooz
----Music Prostitute: The Remixes
--Psy-Trance
----Music Prostitute: The Remixes
--Downtempo
----Transient Dawn
--Ambient
----Transient Dawn
我看到我试图多次添加每张专辑(因为每张专辑都有很多流派),但我不知道如何解决这个问题。
感谢帮助!