实体框架2列有多对一

时间:2017-02-27 15:49:29

标签: c# entity-framework

我有一个包含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 );

当我添加迁移时出现此错误:

  

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

1 个答案:

答案 0 :(得分: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的所有列。您还必须将导航属性从三个删除为一个。