Home > Software design >  Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes.

Time:02-04

I'm Learning Webapi so I'm trying to build a simple Api connected to SQL server and I got this error when I add new Movie data

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details. ---> Microsoft.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Movies_SuperHeroes_HeroId". The conflict occurred in database "SupersDb", table "dbo.SuperHeroes", column 'HeroId'.

I have two models :

Superhero Model:

namespace SuperHeroesApi.Models
{
    public class SuperHero
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int HeroId { get; set; }

        [Required]
        [MaxLength(100)]
        public string Name { get; set; } 

       
        [MaxLength(100)]
        public string FirstName { get; set; } 

        [MaxLength(100)]
        public string LastName { get; set; }

        [MaxLength(100)]
        public string City { get; set; } 










    }
}

Movie Model :

 namespace SuperHeroesApi.Models
{
    public class Movie
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int MovieId { get; set; }

        [Required]
        [MaxLength(100)]
        public string Title { get; set; }

        public int Year { get; set; }

        public double Rate { get; set; }

        public byte [] Poster { get; set; }

        [ForeignKey("SuperHero")]
        public int HeroId { get; set; }
       

        //public string  SuuperHeroName { get; set; }

        public virtual SuperHero SuperHero { get; set; }





    }
}

dto :

namespace SuperHeroesApi.Otds
{
    public class MoviesDtos
    {

        public string Title { get; set; }

        public int Year { get; set; }

        public double Rate { get; set; }

        public IFormFile Poster { get; set; }


        [ForeignKey("SuperHero")]
        public int HeroId { get; set; }



    }
}

MoviesController:

using SuperHeroesApi.Otds;

namespace SuperHeroesApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MoviesController : ControllerBase
    {

        private readonly AppDbContext _dbContext;

        private new List<string> _allowedExtention = new List<string> { "jbg", "png" };
        private long _maxAllowedPosterSize = 5242880;

        public MoviesController(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }


        [HttpGet]
        public async Task<IActionResult>GetAllAsync()
        {
            var movie = await _dbContext.Movies.ToListAsync();

            return Ok(movie);

        }


        [HttpPost]
        public async Task <IActionResult> CreateAsync([FromForm] MoviesDtos dto)
        {
            if (_allowedExtention.Contains(Path.GetExtension(dto.Poster.FileName).ToLower()))
                return BadRequest();

            using var dataStream = new MemoryStream();
            await dto.Poster.CopyToAsync(dataStream);


            var movie = new Movie
            {
                Title = dto.Title,
                Year = dto.Year,
                Rate = dto.Rate,


                Poster = dataStream.ToArray(),
            };

              await _dbContext.AddAsync(movie);
              _dbContext.SaveChanges();

            return Ok(movie);
        }




    }
}

CodePudding user response:

You probably already have existing rows before you made changes to your schema. Now that you're creating a new foreignkey HeroId in movie which cannot be null and an integer for that matter which means it will be a zero by default. It becomes a problem for the existing rows because they will try to reference a Hero entity with Id of 0 which doesn't exist. So, the obvious solution is to make the foreign key nullable and redo the migrations

[ForeignKey("SuperHero")] 
public int? HeroId { get; set; }
  •  Tags:  
  • Related