INSERT语句与FOREIGN KEY约束“ FK_Cars_Owners_OwnerId”冲突

时间:2019-06-18 08:27:20

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

我正在ASP.Net Core 2.2上创建新的WebAPI,并且需要在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; }
}

这是CarsController中的Post方法

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);
        }

此代码行出现错误:

await _carService.AddCarAsync(car);

Debug car controller

DataContext类:

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类方法:

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

执行请求时发生未处理的异常。   Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时发生错误。有关详细信息,请参见内部异常。 ---> System.Data.SqlClient.SqlException:INSERT语句与FOREIGN KEY约束“ FK_Cars_Owners_OwnerId”冲突。在数据库“ CarOwnersDB”的表“ dbo.Owners”的列“ OwnerId”中发生了冲突。

1 个答案:

答案 0 :(得分:1)

似乎您尝试添加Car,该引用引用了不在表Owner中的Owner。这是基本的外键冲突。

首先将Owner的{​​{1}}插入Car表中(或检查是否存在-如果已经存在,则无需执行任何操作),然后插入{{1} }。

因此,您需要执行以下操作:

Owner

在插入汽车之前。