简体   繁体   English

EF Core - 添加相关实体时出错

[英]EF Core - Error when adding a related entity

I get an error when I try to update a related entity of an entity that I already got from database.当我尝试更新已从数据库中获取的实体的相关实体时出现错误。 For illustration purposes I have these entites:出于说明目的,我有这些实体:

    class Car
{
   int Id ..;
   string Name ..;
   virtual ICollection<TireCar> tires ...;
}

class TireCar
{
  int Id ..;
  int TireId ..;
  int CarId..;
  int Size..;
  virtual TireBrand tire;
  virtual Car car;
}

class TireBrand
{
  int Id;
  string Name ..;
}

So, I'm trying to make a Patch method that allows me to update the Car data and also adds, updates or deletes the tires .因此,我正在尝试创建一个 Patch 方法,该方法允许我更新Car数据并添加、更新或删除tires The problem happens when I get the Car entity and after that I add a Tire .当我获得Car实体然后我添加一个Tire Something like that:类似的东西:

    void UpdateCar()
    {
        var car = carService.Get(...);

        ...

        carService.AddTire(new TireCar{ CarId = car.Id, TireId = 1 });

        ...
    }

I'm using the Repository pattern with DI, so the context is the same.我将 Repository 模式与 DI 一起使用,因此上下文是相同的。 The error that is throwing is:抛出的错误是:

System.InvalidOperationException: The association between entity types 'Car' and 'TireCar' has been severed but the foreign key for this relationship cannot be set to null. System.InvalidOperationException:实体类型“汽车”和“轮胎汽车”之间的关联已被切断,但此关系的外键不能设置为空。 If the dependent entity should be deleted, then setup the relationship to use cascade deletes.'如果应该删除依赖实体,则设置关系以使用级联删除。

I tried two things that worked but I think is not the solution:我尝试了两件事,但我认为这不是解决方案:

  • When I get the Car after adding the Tires添加轮胎后拿到车时
  • When I get the Car as no tracking当我因为没有跟踪而拿到车时

Why that happend if I'm updating another tables?如果我更新另一个表,为什么会发生这种情况? What Can I do to solve this?我能做些什么来解决这个问题?

Your issue is actually a configuration issue, not an issue with EF Core.您的问题实际上是配置问题,而不是 EF Core 的问题。 Read carefully what the error says:仔细阅读错误内容:

The association between entity types 'Car' and 'TireCar' has been severed but the foreign key for this relationship cannot be set to null .实体类型 'Car' 和 'TireCar' 之间关联已被切断,但此关系的外键不能设置为 null If the dependent entity should be deleted, then setup the relationship to use cascade deletes.如果应该删除依赖实体,则将关系设置为使用级联删除。

Entity Framework Core has by default (.NET Core 2.0 forward) a SET NULL policy when a dependent entity becomes orphan. Entity Framework Core 在默认情况下(.NET Core 2.0 向前)在依赖实体变为孤立实体时具有SET NULL策略。 If we look carefully at your TireCar model, you are not setting the CarId property as nullable, so the column cannot be set to null.如果我们仔细查看您的TireCar模型,您没有将CarId属性设置为可为空,因此该列不能设置为空。

You have two different solutions to fix this.您有两种不同的解决方案来解决这个问题。 If you want the TireCar entity to get deleted when you remove it from your Car entity, then setup cascade deletes for this relationship (You can also change the EF Core default policy).如果您希望在从Car实体中删除TireCar实体时将其删除,请为此关系设置级联删除(您还可以更改 EF Core 默认策略)。 This can be setup in your DbContext via FluentApi .这可以通过FluentApi在您的DbContext设置。

class MyContext : DbContext
{
    // Your DbSets

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TireCar>()
            .HasOne(tc => tc.car)
            .WithMany(car => car.tires)
            .OnDelete(DeleteBehavior.Cascade);
    }
}

Another solution is to let the TireCar entity have null values in the CarId column, simply changing your entity model like this.另一种解决方案是让TireCar实体在CarId列中具有null值,只需像这样更改您的实体模型。

class TireCar
{
    public int Id  { get; set; }
    public int TireId { get; set; }
    public int? CarId { get; set; }
    public int Size { get; set; }
    public virtual TireBrand tire { get; set; }
    public virtual Car car { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM