'FK_Ratings_Users_UserId' on table 'Ratings' 可能会导致循环或多个级联路径

'FK_Ratings_Users_UserId' on table 'Ratings' may cause cycles or multiple cascade paths

我正在 .NET EFCore 中尝试通过以下实体进行以下 Code-First 迁移

用户

[Table("Users")]
public class User
{
    [Key]
    public int Id { get; set; }

    [Required]
    [MaxLength(100)]
    public string FirstName { get; set; }

    [Required]
    [MaxLength(100)]
    public string LastName { get; set; }

    [Required]
    [MaxLength(250)]
    public string Email { get; set; }

    [Required]
    [MinLength(8), MaxLength(16)]
    public string Password { get; set; }

    [Required]
    [MinLength(6), MaxLength(15)]
    public string Phone { get; set; }

    public ICollection<Apartment> Apartments { get; set; }

    public ICollection<Rating> Ratings { get; set; }
}

公寓

[Table("Apartments")]
public class Apartment
{
    [Key]
    public int Id { get; set; }

    [Required]
    [MinLength(24), MaxLength(100)]
    public string Title { get; set; }

    [Required]
    [MinLength(24), MaxLength(250)]
    public string Address { get; set; }

    [Required]
    public int Price { get; set; }

    [ForeignKey("User")]
    public int UserId { get; set; }

    public User User {get; set;}

    public ICollection<Rating> Ratings { get; set; }

    public ICollection<AptCateg> AptsCategs { get; set; }
}

评分

[Table("Ratings")]
public class Rating
{
    [Key]
    public int Id { get; set; }

    public int Value { get; set; }

    [ForeignKey("Apartment")]
    public int ApartmentId { get; set; }

    public Apartment Apartment { get; set; }

    [ForeignKey("User")]
    public int UserId { get; set; }

    public User User { get; set; }
}

我使用命令 dotnet ef migrations add InitialDatabase 但是当我尝试使用 dotnet ef database update 它会在 cmd 中抛出以下错误,如标题

'FK_Ratings_Users_UserId' on table 'Ratings' may cause cycles or multiple cascade paths

我尝试在 here the modelBuilder's Cascade behavior but it doesn't work because I am getting the same error. I have also tried doing the answer from hereEFCore 教程中添加,但是即使尝试安装 [=19],HasRequired 的实现也不起作用=].

我了解到正在进行的通告 thingy 存在问题。根据我的直觉,该程序不知道在删除用户的情况下该怎么做,是否删除其评级和公寓或类似的东西,这就是它以这种方式行事的原因,但我无法修复问题。

我的问题是,我无法创建我的数据库,因此无法继续处理该项目,我该如何解决这个问题。

谢谢!

您将 UserA​​partment 添加到 Ratings 导致循环引用实体。 UserA​​partment 实体已经与 Ratings 集合建立了一对多关系。

'FK_Ratings_Users_UserId' on table 'Ratings' may cause cycles or multiple cascade paths

Ratings 实体应如下所示:

[Table("Ratings")]
public class Rating
{
    [Key]
    public int Id { get; set; }

    public int Value { get; set; }
}

您必须在其中一个表中将用户关系设为可选,例如:

public int? UserId { get; set; }

使 属性 类型可为 null 告诉 EF 这里不需要级联删除。