我正在使用名為 MusicChannel 的 SQL 資料庫,該資料庫將保存新添加的藝術家歌曲。當我嘗試添加一些東西時,它給了我一個錯誤說:
SqlException: INSERT 陳述句與 FOREIGN KEY 約束“FK__Songs__ArtistID__36B12243”沖突。沖突發生在資料庫“MusicChannel”、表“dbo.Artists”、“ArtistID”列中。該陳述句已終止。< 我按照藝術家、音樂型別和歌曲的順序創建了表格。歌曲有 2 個 FK 作為 ArtistID 和 MusicTypeID。藝術家的PK是ArtistID。MusicTypes 的 PK 是 MusicTypeID。發生這種情況是因為名稱相同嗎?
這是模型:
public IActionResult Insert(NewSongVm formContent)
{
if (formContent.MusicTypeID == -1)
{
//
}
MusicChannelContext ctx = new MusicChannelContext();
Song song = new Song();
Artist artist = new Artist();
song.SongID = formContent.SongID;
song.SongName = formContent.SongName;
song.SongLength = formContent.SongLength;
song.SongLink = formContent.SongLink;
song.MusicTypeID = formContent.MusicTypeID;
song.ArtistID = formContent.ArtistID;
artist.ArtistID = formContent.ArtistID;
artist.ArtistName = formContent.ArtistName;
ctx.Artists.Add(artist);
ctx.Songs.Add(song);
ctx.SaveChanges();
return View();
}
//context:
public class MusicChannelContext:DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("server=.;database=MusicChannel;trusted_connection=true;");
}
public DbSet<Song> Songs { get; set; }
public DbSet<Artist> Artists { get; set; }
public DbSet<MusicType> MusicTypes { get; set; }
}
[1]: https://i.stack.imgur.com/Sy40A.png
uj5u.com熱心網友回復:
您需要保存藝術家表中的更改,添加命令不會在資料庫中創建記錄,
從資料庫中的表中洗掉 FK 約束的另一種解決方案,然后您可以按您想要的任何順序創建記錄。
檢查流動樣品:
MusicChannelContext ctx = new MusicChannelContext();
Artist artist = new Artist();
ctx.Artists.Add(artist);
artist.ArtistID = formContent.ArtistID;
artist.ArtistName = formContent.ArtistName;
ctx.SaveChanges();
Song song = new Song();
song.SongID = formContent.SongID;
song.SongName = formContent.SongName;
song.SongLength = formContent.SongLength;
song.SongLink = formContent.SongLink;
song.MusicTypeID = formContent.MusicTypeID;
song.ArtistID = formContent.ArtistID;
ctx.Songs.Add(song);
ctx.SaveChanges();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371310.html
標籤:C# sql sql-server asp.net核心
