2021-12-03

SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint - asp.net-core

I am using a SQL database called as MusicChannel which will hold the new added songs with artists. When I try to add something, it gives me a error saying:

SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Songs__ArtistID__36B12243". The conflict occurred in database "MusicChannel", table "dbo.Artists", column 'ArtistID'. The statement has been terminated. < I created the table in order of Artists, MusicTypes and Songs. Songs have 2 FK as ArtistID and MusicTypeID. Artists' PK is ArtistID. MusicTypes' PK is MusicTypeID. Is this happening because the names are the same?

Here is the Model:

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


from Recent Questions - Stack Overflow https://ift.tt/3pj0HpH
https://ift.tt/eA8V8J

No comments:

Post a Comment