表'评级'上的'FK_Ratings_Users_UserId'可能导致循环或多个级联路径

问题描述 投票:0回答:2

我正在尝试在.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'可能导致循环或多个级联路径

我尝试在here的EFCore教程中添加了模型构建器的Cascade行为,但它不起作用,因为我得到了同样的错误。我也试过从here做出答案,但即使尝试安装HasRequiredEntityFrameworkCore.Tools的实现也无法正常工作。

我知道存在一个循环问题的问题。根据我的直觉,程序不知道在删除用户的情况下该做什么,是否放弃其评级和公寓或某种类型,这就是为什么它以这种方式行事,但我无法修复问题。

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

谢谢!

asp.net-core foreign-keys ef-migrations
2个回答
2
投票

您必须在其中一个表上使用户关系可选,例如:

public int? UserId { get; set; }

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


0
投票

通过将用户和公寓添加到评级实体,您将导致循环引用。用户和公寓实体已经与Ratings集合建立了一对多的关系。

表'评级'上的'FK_Ratings_Users_UserId'可能导致循环或多个级联路径

这是评级实体的样子:

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

    public int Value { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.