简体   繁体   中英

How to solve System.Data.Entity.Infrastructure.DbUpdateException

The INSERT statement conflicted with the FOREIGN KEY constraint FK_dbo.CinemaShowTime_dbo.Cinema_cinemaId . The conflict occurred in database " CinemaModule ", table " dbo.Cinema ";

I am successfully saving the result of Cinema in DB but when I try to save movie or CreateCinemasShowTime it give me error.

I am trying to render multiple models into single view but DBUPdateException occurs.

My Controller code

        var cinema = new Cinema();
        cinema.Halls = viewModel.Halls;
        cinema.ContactNumber = viewModel.ContactNumber;
        cinema.TicketFee = viewModel.TicketFee;


        var movie = new Movies();
        movie.MovieName = viewModel.MovieName;
        movie.MovieBio = viewModel.MovieBio;
        movie.MoviePosterUrl = viewModel.MoviePosterUrl;



        var cinemaShowtime = new CinemaShowTime();
        cinemaShowtime.ShowDay = viewModel.ShowDay;
        cinemaShowtime.ShowTime = viewModel.ShowTime;

        db.CinemaShowTimes.Add(cinemaShowtime);
        db.SaveChanges();

My Model Code

    public int Id { get; set; }
    public string MovieName { get; set; }//
    public string MoviePosterUrl { get; set; }//
    public string MovieBio { get; set; }

    //collection of CinemaShowTimes for single movie
    public virtual ICollection<CinemaShowTime> CinemaShowTimes { get; set; }

    //single industry for each Movie
    [ForeignKey("IndustriesInstance")]
    public int? IndustryId { get; set; }
    //reference navigation property
    public virtual Industries IndustriesInstance { get; set; }

Here I solved the problem by simply referencing the movie object towards it's join/relational table

var movie = new Movies();
movie.MovieName = viewModel.MovieName;
movie.MovieBio = viewModel.MovieBio;
movie.MoviePosterUrl = viewModel.MoviePosterUrl;

Towards the reference navigation key which is present in the join table/navigational table like this

 cinemaShowtime.CinemaInstance = cinema;
 cinemaShowtime.MoviesInstance = movie; 

Also the system was asking to make the composite key nullable which is present in Movie Table table like this

 public int? IndustryId { get; set; }

It should be noted that I am making many-to-many relationship same thing would happen for cinema table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM