如何从一个实体配置2个外键引用

时间:2017-10-03 20:23:00

标签: entity-framework-6

我正在尝试为包含边和节点的图形设置模型。每个节点都有一个指向传入和传出边的链接。反之亦然。

当我使用2个节点和它们之间的一个边缘填充新的实体框架上下文,然后调用SaveAllChanges()时,它失败并出现以下错误:

无法确定' Test.Node_Incoming'的主要结尾。关系。多个添加的实体可能具有相同的主键。

这是SQL Server模型:

 CREATE TABLE [dbo].[Node] (
    [NodeId] INT IDENTITY (1,1) NOT NULL,
    [Name] VARCHAR (200) NOT NULL,
 );

 CREATE TABLE [dbo].[Edge] (
    [EdgeId] INT IDENTITY (1, 1) NOT NULL,
    [StartNodeId] INT NOT NULL,
    [EndNodeId] INT NOT NULL,
    PRIMARY KEY CLUSTERED ([NodeId] ASC),
 );

 ALTER TABLE [dbo].[Edge]
    ADD CONSTRAINT [FK_Edge_EndNode] FOREIGN KEY ([EndNodeId]) REFERENCES [dbo].
 [Node] ([NodeId]);
ALTER TABLE [dbo].[Edge]
    ADD CONSTRAINT [FK_Edge_StartNode] FOREIGN KEY ([StartNodeId]) REFERENCES [dbo].[Node] ([NodeId]);

这是EF模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Test
{
    [Table("Node")]
    public class Node
    {
        public Node()
        {
            Incoming = new List<Edge>();
            Outgoing = new List<Edge>();
        }

        [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int NodeId { get; set; }
        public string Name { get; set; }

        [ForeignKey("StartNodeId")]
        public virtual ICollection<Edge> Outgoing { get; set; }

        [ForeignKey("EndNodeId")]
        public virtual ICollection<Edge> Incoming { get; set; }
    }

    [Table("Edge")]
    public class Edge
    {
        [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int EdgeId { get; set; }

        [ForeignKey("StartNodeId")]
        public Node StartNodeRef { get; set; }
        public int StartNodeId { get; set; }


        [ForeignKey("EndNodeId")]
        public Node EndNodeRef { get; set; }
        public int EndNodeId { get; set; }
    }
}

希望有人能告诉我如何解决这个问题,

提前致谢! 的Jeroen

0 个答案:

没有答案