The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Cars_Owners_OwnerId"

asp.net-core asp.net-core-webapi c# entity-framework-core sql-server

Question

I'm creating a new WebAPI on ASP.Net Core 2.2 and I need to define a relationships between two models in SQL Server:

Car

public class Car
{
    [Key]
    public Guid CarId { get; set; }
    public string Brand { get; set; }
    public Guid OwnerId { get; set; }
    public Owner Owner { get; set; }
}

Owner

public class Owner
{
    [Key]
    public Guid OwnerId { get; set; }
    public string Name { get; set; }
    public string Phone { get; set; }
    public IEnumerable<Car> Cars { get; set; }
}

This is the Post method in CarsController

private const string AlexGuid = "21fd1de8-ce31-4224-b0b1-39e3f9dbaa18";
...
[HttpPost(ApiRoutes.Cars.Create)]
        public async Task<IActionResult> Add([FromBody] CreateCarRequest carRequest)
        {
            var car = new Car { Brand = carRequest.Brand };

            if (car.CarId == Guid.Empty)
            {
                car.CarId = Guid.NewGuid();
            }

            if (car.Owner.OwnerId == Guid.Empty)
            {
                car.OwnerId = Guid.Parse(AlexGuid);
            }

            await _carService.AddCarAsync(car);

            var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}";
            var locationUri = baseUrl + "/" + ApiRoutes.Cars.Get.Replace("{carId}", car.CarId.ToString());

            var response = new CarResponse { CarId = car.CarId };
            return Created(locationUri, response);
        }

The error occurs at this line of code:

await _carService.AddCarAsync(car);

Debug car controller

DataContext class:

public class DataContext : IdentityDbContext
    {
        public DataContext(DbContextOptions<DataContext> options) : base(options)
        {
        }

        public DbSet<Car> Cars { get; set; }
        public DbSet<Owner> Owners { get; set; }

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

            modelBuilder.Entity<Owner>()
                .HasMany(c => c.Cars)
                .WithOne(e => e.Owner);
        }
    }

CarService class method:

public async Task<bool> AddCarAsync(Car car)
        {
            await _dataContext.Cars.AddAsync(car);
            var added = await _dataContext.SaveChangesAsync();
            return added > 0;
        }

An unhandled exception has occurred while executing the request. Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Cars_Owners_OwnerId". The conflict occurred in database "CarOwnersDB", table "dbo.Owners", column 'OwnerId'.

1
0
6/18/2019 9:05:37 AM

Accepted Answer

It appears that you try to add Car, which references Owner that is not in the table Owner. That's basic foreign key violation.

First insert Owner of a Car to a Owner table (or check for existence - if it already exists, then nothing needs to be done), then insert Car.

So you need to do something like:

await _dataContext.Owners.AddAsync(car.Owner);

before inserting a car.

1
6/18/2019 8:33:47 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow