2015-09-02 26 views
2

我有以下型号:如何解决“多重性在角色中无效”错误?

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; } 
} 

我试图定义一个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 

我收到错误

Product_Retailer_Source::多重性在'Product_Retailer'关系中的角色'Product_Retailer_Source'中无效。由于依赖角色是指关键属性,所以依赖角色的多重性的上界必须是'1'。

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

+0

如何被定义的ID? –

+0

我认为你应该使用HasOptional代替HasRequired – Arash

+0

ID在Asp.net样板解决方案的定义,所以它的定义是不提供给我。 – DaveDev

回答

2

试试这个

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

利用这种配置(你没有定义存储对产品的RetailerId外键)

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

你说得对,但你也应该指出'.HasForeignKey(p => p.Id)'是完全错误的。它将自己的主键标记为外键。 –

相关问题