代码优先主键违规

Code-First Primary Key Violation

我是代码优先的新手,但喜欢它。我有一个继承结构:节点通过连接 class 耦合。但是,我怀疑由于基础和派生 classes 之间的 PK、FK 关系,存在主键冲突。

Violation of PRIMARY KEY constraint 'PK_dbo.Connections'. Cannot insert duplicate key in object 'dbo.Connections'

所以,不是数据库 Mack-O-Grady,我想知道这是否可行?

public abstract class Node 
{
    public Guid Id { get; set; } 
}

[Table("Node1")]
public class Node1 : Node { }

[Table("Node2")]
public class Node2 : Node { }

[Table("Node3")]
public class Node3 : Node { }

public class Connection
{
    public Guid Id { get; set; }
    public Node Parent { get; set; }
    public int ParentPort { get; set; }
    public Node Child { get; set; }
}

public class TestContext : DbContext
{
    public TestContext() : base("TST")
    {
        var ensureDLLIsCopied = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
    }

    public DbSet<Node> Nodes { get; set; }
    public DbSet<Connection> Connections { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var nodes = new List<Node>();

        using (var context = new TestContext())
        {
            var n1 = new Node1
            {
                Id = Guid.NewGuid(),
            };

            nodes.Add(n1);
            context.Nodes.Add(n1);

            var n2 = new Node2
            {
                Id = Guid.NewGuid(),
            };

            nodes.Add(n2);
            context.Nodes.Add(n2);

            var n3 = new Node2
            {
                Id = Guid.NewGuid(),
            };

            nodes.Add(n3);
            context.Nodes.Add(n3);

            var c1 = new Connection { Parent = n1, ParentPort = 0, Child = n2 };
            context.Connections.Add(c1);

            var c2 = new Connection { Parent = n2, ParentPort = 0, Child = n3 };
            context.Connections.Add(c2);

            context.SaveChanges();  // exception when saving????

            Console.ReadLine();
        }
    }
}

答案是因为 Id 属性(未设置主键) var c1 = new Connection { Id = Guid.NewGuid(), Parent = n1, ParentPort = 0, Child = n2 }; context.Connections.Add(c1); var c2 = new Connection { Id = Guid.NewGuid(), Parent = n2, ParentPort = 0, Child = n3 }; context.Connections.Add(c2);