Search code examples
c#.netsql-serverentity-framework

Microsoft.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FK


I'm creating a POST API to insert data into my Walks table and it has two ForeignKey with Difficulties and Regions table and this is my Walk model

public class Walk
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public double LengthInKm { get; set; }
    public string? WalkImageUrl { get; set; }
    
    public Guid DifficultyId { get; set; }
    public Guid RegionId { get; set; }
   

    public Difficulty Difficulty { get; set; }
    public Region Region { get; set; }
}

I don't know why conflict happen because I checked the all the table and model. I seeded data in Regions and Difficulty and it's still not working.

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions options) : base(options)
    {
        
    }
    public DbSet<Difficulty> Difficulties { get; set; }
    public DbSet<Region> Regions { get; set; }
    public DbSet<Walk> Walks { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        var difficuties = new List<Difficulty>()
        {
            new Difficulty()
            {
                Id = Guid.Parse("ce6a68d1-b490-4d38-a162-21ce3c371bfa"),
                Name = "Easy"
            },
            new Difficulty()
            {
                Id = Guid.Parse("f5a9b531-a099-493a-a05a-81c95627adbc"),
                Name = "Medium"
            },
            new Difficulty()
            {
                Id = Guid.Parse("261f60b6-efa7-426d-8ea4-7b34cf9beba1"),
                Name = "Hard"
            }
        };
        modelBuilder.Entity<Difficulty>().HasData(difficuties);


        var regions = new List<Region>()
        {
            new Region
            {
                Id = Guid.Parse("3a5d1dd2-abc5-412b-9e3d-c1b2648a228f"),
                Name = "Ha Noi",
                Code = "HN",
                RegionImageUrl = ""
            },
            new Region
            {
                Id = Guid.Parse("22715dff-abad-4263-837a-9e97d80fa86d"),
                Name = "Sai Gon",
                Code = "SG",
                RegionImageUrl = ""
            },
             new Region
             {
                 Id = Guid.Parse("bc562c11-d7b2-478b-a75d-56a8da71b85a"),
                 Name = "Da Nang",
                 Code = "DN",
                 RegionImageUrl = ""
             },
             new Region
             {
                 Id = Guid.Parse("76675766-473f-4d1d-aba3-e4673f805d0c"),
                 Name = "Ninh Binh",
                 Code = "NB",
                 RegionImageUrl = ""
             }
        };
        modelBuilder.Entity<Region>().HasData(regions);
   
    }
}

That is my dbcontext where I seeded some data

This is my Controller

private readonly IMapper mapper;
private readonly IWalkRepository walkRepository;

public WalksController(IMapper mapper, IWalkRepository walkRepository)
{
    this.mapper = mapper;
    this.walkRepository = walkRepository;
}
[HttpPost]
public async Task<IActionResult> Create([FromBody] CreateAndUpdateWalkDTO createAndUpdateWalkDTO)
{
    // map from createDTO to model
    var createWalkModel = mapper.Map<Walk>(createAndUpdateWalkDTO);

    await walkRepository.CreateAsync(createWalkModel);

    //map from model to dto to return
    return Ok(mapper.Map<WalkDTO>(createWalkModel));
}

Create and Update DTO

public class CreateAndUpdateWalkDTO
{
    public string Name { get; set; }
    public string Description { get; set; }
    public double LengthInKm { get; set; }
    public string? WalkImageUrl { get; set; }
    public Guid DiffcultyId { get; set; }
    public Guid RegionId { get; set; }


}

Walk DTO

public class WalkDTO
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public double LengthInKm { get; set; }
    public string? WalkImageUrl { get; set; }
    public Guid DiffcultyId { get; set; }
    public Guid RegionId { get; set; }
}

My object i send from client

{
  "name": "Name",
  "description": "This is description",
  "lengthInKm": 10,
  "walkImageUrl": null,
  "diffcultyId": "f5a9b531-a099-493a-a05a-81c95627adbc",
  "regionId": "3a5d1dd2-abc5-412b-9e3d-c1b2648a228f"
}

Solution

  • After many days of trying, I realized my stupidity came from creating and sending the wrong object. This is wrong object

    {
      "name": "Name",
      "description": "This is description",
      "lengthInKm": 10,
      "walkImageUrl": null,
      "diffcultyId": "f5a9b531-a099-493a-a05a-81c95627adbc",
      "regionId": "3a5d1dd2-abc5-412b-9e3d-c1b2648a228f"
    }
    

    and the problem is the "diffcultyId" spelling mistake. It has to be "diffcultyId"