两个连接类中的Entity Framework外键错误

时间:2014-07-14 09:49:37

标签: c# asp.net-mvc entity-framework-6.1

我在ASP.NET MVC中使用Entity Framework 6.1。

我的模特是:

public class Article
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public double Price { get; set; }

    [InverseProperty("Article")]
    public virtual ICollection<FormulaItem> FormulaItem { get; set; }
}

public class FormulaItem
{
    [Key]
    [Column(Order = 0)]
    public int Id { get; set; }

    [ForeignKey("IdMaster")]
    public virtual Formula Formula { get; set; }
    public int IdMaster { get; set; }

    [ForeignKey("IdArticle")]
    public virtual Article Article { get; set; }
    public int IdArticle { get; set; }

    public string Comment { get; set; }
    public int Count { get; set; }
}

public class Formula
{
    [Key]
    [Column(Order = 0)]

    public int Id { get; set; }
    public FormulaMode Mode { get; set; }

    // Wen add this line I get error  
    //[ForeignKey("IdArticle")]        
    //public virtual Article Article { get; set; }
    //public int? IdArticle { get; set; }               

    public string Comment { get; set; }
    public virtual IList<FormulaItem> Items { get; set; }

    public Formula()
    {
        Items = new List<FormulaItem>();
    }
}   

此示例工作正常,但添加新poco:

    // When I add this line in class formula I get error  
    [ForeignKey("IdArticle")]        
    public virtual Article Article { get; set; }
    public int? IdArticle { get; set; } 

到班级Formula我收到错误:

  

Formula_Items_Source_Formula_Items_Target ::关系约束中的从属角色和主要角色中的属性数必须相同

2 个答案:

答案 0 :(得分:0)

考虑使用FluentAPI,因为它更加用户友好:

    modelBuilder.Entity<FormulaItem>()
        .HasOptional(b => b.Article )
        .WithMany(a => a.FormulaItem);

在您的情况下,您必须缺少另一个InverseProperty属性:

[InverseProperty("FormulaItem")]
public virtual Article Article { get; set; }

答案 1 :(得分:0)

我补充说:

modelBuilder.Configurations.Add(new FormulaConfig());
public class FormulaConfig : EntityTypeConfiguration<Formula>
{
    public FormulaConfig()
    {               // one-to-many
        this.HasRequired(x => x.Article)
            .WithOptional(x=>x.Formula)         
            .WillCascadeOnDelete();

    }
}

但得到错误:

Article_Formula_Target :: Multiplicity在关系'Article_Formula'中的角色'Article_Formula_Target'中无效。由于Dependent Role属性不是关键属性,因此Dependent Role的多重性的上限必须为'*'。