使用EF代码首先存储图 [英] Storing graph with EF Code First
问题描述
我试图将图形保存到数据库中,如此处与EF代码首先。
I'm trying to save a graph into a database as described here with EF Code First.
我用相邻节点的集合定义属性:
I defined property with collection of adjacent nodes:
public class Node {
public int NodeId { get; set; }
public string NodeName { get; set; }
public ICollection<Node> Nodes { get; set; }
}
但EF只为此模型生成了一个表:
but EF generated only one table for this model:
dbo.Nodes
NodeId (PK, int, not null)
NodeName (nvarchar(max), null)
Node_NodeId (FK, int, null)
如何强制EF生成多对多关系?
How to force EF to generate many-to-many relationship?
有没有其他方法可以在数据库中存储图形?
Are there any other ways to store graphs in the database?
推荐答案
您的类模型表示 Node
具有一个节点集合,可以由生成的表完全容纳。如果你想要多对多,你必须告诉EF你的计划。
Your class model expresses that a Node
has one collection of nodes, which can be fully accommodated by the generated table. If you want many-to-many, you'll have to tell EF about your plans.
你可以做的一件事是做父母和孩子的集合:
One thing you can do is make parent and child collections:
public class Node
{
public int Id { get; set; }
public string NodeName { get; set; }
public ICollection<Node> ParentNodes { get; set; }
public ICollection<Node> ChildNodes { get; set; }
}
EF将创建一个连接表,如下所示:
EF will create a join table as follows:
[dbo].[NodeNodes]
[Node_Id] [int] NOT NULL,
[Node_Id1] [int] NOT NULL
如果您想要更有意义的列名称,您可以这样做:
If you want more meaningful names of the columns you could do this:
class NodeContext : DbContext
{
public DbSet<Node> Nodes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Node>()
.HasMany(n => n.ParentNodes)
.WithMany(n => n.ChildNodes)
.Map(c => c.MapLeftKey("ChildNodeId")
.MapRightKey("ParentNodeId"));
}
}
尝试这个:
var root = new Node { NodeName = "Root" };
root.ParentNodes = new List<Node> { new Node { NodeName = "Par1" }, new Node { NodeName = "Par2" } };
root.ChildNodes = new List<Node> { new Node { NodeName = "Ch1" }, new Node { NodeName = "Ch2" } };
con.Nodes.Add(root);
con.SaveChanges();
(其中 con
是一个 NodeContext
实例),看看你喜欢的结果。
(Where con
is a NodeContext
instance) and see if you like the result.
这篇关于使用EF代码首先存储图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!