如何首先在代码中定义两个实体之间的多对多和一对多关系?

how to define many-to-many and one-to-many relations between two entities in code first?

我正在使用实体框架代码优先创建网站,其中: 用户可以销售很多产品:一对多。 用户可以购买很多产品,产品可以被很多用户购买:多对多。 我不断收到错误消息:

System.Data.SqlClient.SqlException: 'Introducing FOREIGN KEY constraint 'FK_dbo.UserProducts_dbo.Products_Product_ProductId' on table 'UserProducts' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

我确实想要级联删除,以便删除属于已删除其帐户的用户的产品,或从属于已删除用户或已删除产品的 UserProduct table 中删除记录。 我做错了什么?

这是用户 class:

public class User
{
    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }


    public ICollection<Product> Products { get; set; }
    [InverseProperty("Users")]
    public ICollection<Product> Cart { get; set; }

    public User()
    {
        Products = new List<Product>();
        Cart = new List<Product>();
    }
}

这是产品 class:

public class Product
{
    [Key]
    public int ProductId { get; set; }
    public int OwnerId { get; set; }
    public string Title { get; set; }
    public string ShortDescription { get; set; }
    public string LongDescription { get; set; }

    public byte[] Picture1 { get; set; }
    public byte[] Picture2 { get; set; }
    public byte[] Picture3 { get; set; }

    [ForeignKey("OwnerId")]
    public User User { get; set; }
    public ICollection<User> Users { get; set; }

    public Product()
    {
        Users = new List<User>();
    }
}

首先我需要为 many-to-many 关系中的中间 table 写一个 class users-to-products:

public class UserProduct
{
    [Key, Column(Order = 0), ForeignKey("User")]
    public int UserId { get; set; }
    [Key, Column(Order = 1), ForeignKey("Product")]
    public int ProductId { get; set; }

    public User User { get; set; }
    public Product Product { get; set; }
}

允许我禁用从这个 table 到用户 table 的级联删除(覆盖上下文 class 中的 OnModelCreating):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<UserProduct>().HasRequired(t => 
        t.User).WithMany(t => t.Cart).WillCascadeOnDelete(false);
    }

禁用级联有效是因为:

  1. 解决了多级联路径错误
  2. 删除用户仍然会删除他的产品和他们的 UserProducts, 删除产品将删除其 UserProducts。