【问题标题】:Entity Framework 6 Multiplicity is not valid?实体框架 6 多重性无效?
【发布时间】:2020-03-26 22:38:36
【问题描述】:

我有两个表,我想在其中实现 1-1 关系。我遇到了这篇文章中描述的问题: EntityFramework : Invalid column name *_ID1 我尝试实施解决方案,添加外键属性,但遇到了另一个问题:

多重性在关系“Account_Companies”中的角色“Account_Companies_Target”中无效。因为从属角色属性不是关键属性,所以从属角色的多重性的上限必须是'*'。

这些是类:

 public class Account
{
    [Key]
    public Guid Id { get; set; }
    public string CompanyName { get; set; }
    public long CNP { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public long PhoneNumber { get; set; }
    public string Address { get; set; }
    [Required]
    public string UserName { get; set; }

    [Required(ErrorMessage = "Password is Required.")]
    public string Password { get; set; }
    public DateTime CreatedOn { get; set; }

    [NotMapped]
    [Required(ErrorMessage = "Confirmation Password is Required")]
    [Compare("Password", ErrorMessage = "Password Must Match")]
    public string ConfirmPassword { get; set; } 

    [Required]
    public AccountType AccountType { get; set; }

    public int CUI { get; set; }

    [ForeignKey("Id")]
    public virtual Company Companies { get; set; }

}

   public class Company
{

    [Key]
    public long CUI { get; set; }
    public Guid Id { get; set; }
    public string CompanyName { get; set; }
    public string Simbol { get; set; }
    public int SharesCount { get; set; }
    public decimal SharePrice { get; set; }
    public virtual Account Account { get; set; }

}

这是 OnModelCreating 覆盖:

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Account>()
           .HasOptional(account => account.Companies)
           .WithRequired(company => company.Account);            
    }

【问题讨论】:

  • 我不会将属性与 fluent 混合使用 - 坚持使用 fluent。 HasOptional 意味着可以为空的 FK。我也会称“公司”为“公司”,因为它不是一个集合。

标签: c# asp.net entity-framework-6


【解决方案1】:

如果外键属性 Account.CUI 不是键,则关系是 1:many,而不是 1:1。而 EF6 只允许一个实体拥有一个键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    相关资源
    最近更新 更多