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);
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'.
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.