【问题标题】:How to resolve " Multiplicity is not valid in Role" error?如何解决“多重性在角色中无效”错误?
【发布时间】:2015-09-02 11:45:54
【问题描述】:

我有以下型号:

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'。

我定义这种关系的方式有什么问题?我该如何解决这个问题?

【问题讨论】:

  • ID是如何定义的?
  • 我认为你应该使用 HasOptional 而不是 HasRequired
  • ID 是在 Asp.net BoilerPlate 解决方案中定义的,所以它的定义对我不可用。
  • @DaveDev: 但它是否可以为空?

标签: c# entity-framework


【解决方案1】:

试试这个

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

【讨论】:

  • 你是对的,但你也应该指出.HasForeignKey(p =&gt; p.Id) 是完全错误的。它将自己的主键标记为外键。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多