如何解决“多重性在角色中无效”错误?

我有以下型号:

public class Retailer : Entity { public string Name { get; set; } public string Address { get; set; } public virtual ICollection Products { get; set; } public virtual ICollection Customers { get; set; } } public class Product : Entity { public string Name { get; set; } public string Description { get; set; } public string ECommerceUrl { get; set; } public string ImageUrl { get; set; } public Retailer Retailer { get; set; } public ICollection Categories { get; set; } } 

我正在尝试定义一个1到(0或多个)关系,其中零售商可以拥有0个或多个具有以下内容的产品:

 modelBuilder.Entity() .HasRequired(r => r.Retailer) .WithMany(p => p.Products) .HasForeignKey(p => p.Id); // Id is defined in the base class 

我收到了错误

Product_Retailer_Source :: Multiplicity在关系’Product_Retailer’中的角色’Product_Retailer_Source’中无效。 由于“从属角色”是指关键属性,因此从属角色的多重性的上限必须为“1”。

我如何定义关系有什么问题? 我怎样才能解决这个问题?

试试这个

 public class Product : Entity { public Retailer Retailer { get; set; } public int RetailerId { get; set; } } 

使用此配置(您没有定义外键来存储RetailerId对产品)

 modelBuilder.Entity() .HasRequired(r => r.Retailer) .WithMany(p => p.Products) .HasForeignKey(p => p.RetailerId);