2017-02-27 102 views
1

我有一個2列的表,這2列有一個表的參考。實體框架2列與多對一

我首先使用了實體框架代碼,但我嘗試構建遷移時無法使用該方法。

「父」:

public class NodesTree 
{ 
    public NodesTree(){ 
     this.ActualTreeNode = new List<TreePath>(); 
     this.NextTreeNode = new List<TreePath>(); 
    } 

    public int TreeId { get; set; } 

    public virtual Tree Tree { get; set; } 

    public virtual ICollection<TreePath> ActualTreeNode { get; set; } 

    public virtual ICollection<TreePath> NextTreeNode { get; set; } 
} 

孩子:

public class TreePath 
{ 
    public TreePath() 
    { 
    } 

    public int NodeId { get; set; } 

    public virtual NodesTree Node { get; set; } 

    public int NextNodeId { get; set; } 

    public virtual NodesTree NextNode { get; set; } 

    public int TreeId { get; set; } 

    public virtual Tree Tree { get; set; } 
} 

的配置我有這方面的定義:

 this.HasRequired(n => n.Node) 
      .WithMany(t => t.ActualTreeNode) 
      .HasForeignKey(n => n.NodeId) 
      .WillCascadeOnDelete(false); 

     this.HasRequired(n => n.NextNode) 
      .WithMany(t => t.NextTreeNode) 
      .HasForeignKey(n => n.NextNodeId) 
      .WillCascadeOnDelete(false); 

當我添加我得到這個錯誤的遷移:

The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical.

回答

1

錯誤的原因是模型中存在錯誤配置的關係。這是不正確的:

this.HasRequired(n => n.Node) 
    .WithMany(t => t.ActualTreeNode) 
    .HasForeignKey(n => n.NodeId) 
    .WillCascadeOnDelete(false); 

this.HasRequired(n => n.NextNode) 
    .WithMany(t => t.NextTreeNode) 
    .HasForeignKey(n => n.NextNodeId) 
    .WillCascadeOnDelete(false); 

它應該是:

this.HasRequired(n => n.Node) 
    .WithMany(t => t.ActualTreeNode) 
    .HasForeignKey(n => new { n.NodeId, n.NextNodeId }) 
    .WillCascadeOnDelete(false); 

因爲相關的FK必須包含主要PK中的所有列。您還必須從三對一移除導航屬性。

+0

仍然有同樣的問題。 – Blackout