【问题标题】:SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint - asp.net-coreSqlException:INSERT 语句与 FOREIGN KEY 约束冲突 - asp.net-core
【发布时间】:2022-01-08 00:17:18
【问题描述】:

我正在使用一个名为 MusicChannel 的 SQL 数据库,它将与艺术家一起保存新添加的歌曲。当我尝试添加一些东西时,它给了我一个错误提示:

SqlException:INSERT 语句与 FOREIGN KEY 约束“FK__Songs__ArtistID__36B12243”冲突。冲突发生在数据库“MusicChannel”、表“dbo.Artists”、列“ArtistID”中。 声明已终止。

我按照 Artists、MusicTypes 和 Songs 的顺序创建了表格。歌曲有 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; }
    }

【问题讨论】:

标签: c# sql sql-server asp.net-core


【解决方案1】:

您需要在Artist表中保存更改,Add命令不会在数据库中创建记录,

另一种解决方案是从数据库中的表中删除 FK 约束,然后您可以按照您想要的任何顺序创建记录。

检查流动样本:

         MusicChannelContext ctx = new MusicChannelContext();
        Artist artist = new Artist();
        artist.ArtistID = formContent.ArtistID;
        artist.ArtistName = formContent.ArtistName;
        ctx.Artists.Add(artist);
        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();

【讨论】:

  • 谢谢。这解决了它。
猜你喜欢
  • 2017-06-29
  • 1970-01-01
  • 2017-05-07
  • 2018-10-12
  • 2019-02-16
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多