代码优先主键违规

时间:2015-01-07 03:59:48

标签: ef-code-first

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

  

违反PRIMARY KEY约束'PK_dbo.Connections'。无法在对象'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();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

答案是因为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);

相关问题