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

C# 如何解决;多重性在角色“”中无效;错误?,c#,entity-framework,C#,Entity Framework,我有以下型号: public class Retailer : Entity { public string Name { get; set; } public string Address { get; set; } public virtual ICollection<Product> Products { get; set; } public virtual ICollection<Customer> Customers { get;

我有以下型号:

public class Retailer : Entity
{
    public string Name { get; set; }
    public string Address { get; set; }
    public virtual ICollection<Product> Products { get; set; }
    public virtual ICollection<Customer> 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<Category> Categories { get; set; }
}
公共类零售商:实体
{
公共字符串名称{get;set;}
公共字符串地址{get;set;}
公共虚拟ICollection产品{get;set;}
公共虚拟ICollection客户{get;set;}
}
公共类产品:实体
{
公共字符串名称{get;set;}
公共字符串说明{get;set;}
公共字符串电子商务URL{get;set;}
公共字符串ImageUrl{get;set;}
公共零售商{get;set;}
公共ICollection类别{get;set;}
}
我试图定义一个1对(0或多)关系,其中零售商可以拥有0个或多个具有以下内容的产品:

modelBuilder.Entity<Product>()
    .HasRequired(r => r.Retailer)
    .WithMany(p => p.Products)
    .HasForeignKey(p => p.Id); // Id is defined in the base class
modelBuilder.Entity()
.HasRequired(r=>r.Retailer)
.有许多(p=>p.产品)
.HasForeignKey(p=>p.Id);//Id是在基类中定义的
我发现了错误

Product\u Retailer\u Source::多重性在关系“Product\u Retailer”中的角色“Product\u Retailer\u Source”中无效。因为依赖角色引用密钥属性,所以依赖角色的多重性上限必须为“1”

我如何定义这种关系有什么问题?如何修复此问题?

试试这个

public class Product : Entity
{
    public Retailer Retailer { get; set; }
    public int RetailerId { get; set; }
}
使用此配置(您没有定义外键来存储针对产品的RetailerId)

modelBuilder.Entity()
.HasRequired(r=>r.Retailer)
.有许多(p=>p.产品)
.HasForeignKey(p=>p.RetailerId);

ID是如何定义的?我想你应该使用HasOptional来代替HasRequiredID,因为它是在Asp.net样板解决方案中定义的,所以它的定义对我来说不可用。@DaveDev:但它是否可以为null?你是对的,但你也应该指出,
HasForeignKey(p=>p.ID)
完全错误。它将自己的主键标记为外键。
modelBuilder.Entity<Product>()
    .HasRequired(r => r.Retailer)
    .WithMany(p => p.Products)
    .HasForeignKey(p => p.RetailerId);