1

I'm Learning web APIs, so I'm trying to build a simple API connected to a SQL server. 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);
        }
    }
}
2
  • 1
    you are referencing superhero in movies, when you then create a new movie, you don't set the heroid. Commented Feb 3, 2022 at 18:40
  • @gsharp hi, do you mean in the movie model or the dot? can you explain more please Commented Feb 3, 2022 at 18:42

2 Answers 2

7

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; }
Sign up to request clarification or add additional context in comments.

2 Comments

I'm curious. You had this answer marked as accepted, then you removed it later. did it not solve your problem?
your answer guided me to a better way to solve my problem and to implement my app better than the way I have planned, so thank you
0

Make sure you are not giving Id by yourself, it will automatically generate it.

If your class look like this

public class Canditate:Entity,IHasCreationTime
{
    [Required]
    public String Name { get;set; } 

    public String Position { get; set; }
    public DateTime CreationTime { get; set ; }

    public Canditate()
    {
        CreationTime = DateTime.Now;    
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.