I have a class as below:
public class Node
{
public int NodeID { get; set; }
public virtual ICollection<Node> Froms { get; set; }
public virtual ICollection<Node> Tos { get; set; }
}
When the Code First mapped it to 2 tables:
And two One to Many Relationship between them,
Now the question is how I can made ef to make 3 Tables as below:
And two One to Many Relationship between Nodes and Froms plus Nodes and Tos
I put two images on my asp.net post that may help asp.net post
MORE DESCRIPTION
Let me describe more, the existing problem:
I am modeling a pipeline system that has a structure like the NODE I have already mentioned. A pipeline may start from many other pipelines and may ends to many another pipelines, for example: number 1 pipeline starts from number 2,3,4 and ends to number 5 and 6 .
The entity framework mapped the pipeline (Node) class to TWO tables as below:
Nodes ========= ID --------- 1 2 3 4 5 6
NodeNodes ============================ Node_NodeID Node_NodeID1 ---------------------------- 1 2 1 3 1 4 5 1 6 1
Great! The EF very smartly put the Starts and Ends in one table, but what the main problem is?!
When a user define starts and ends of number 1 pipeline , if he look at 2,3 and 4 will see they ends to 1 and if he go to 5 and 6 he will see they begins from 1. This additional information (of course they are true) is not desired.
I think about the solution and come up with an idea, if I have two tables for FROMs and TOs ,I won’t have explained problem.
For example:
Froms ============================ Node_NodeID From_NodeID1 ---------------------------- 1 2 1 3 1 4
Tos ============================ Node_NodeID To_NodeID1 ---------------------------- 1 5 1 6
In such case your relations cannot be to Node
class but you must make new From
and To
class.
public class To { ... }
public class From { ... }
public class Node
{
public int NodeID { get; set; }
public virtual ICollection<From> Froms { get; set; }
public virtual ICollection<To> Tos { get; set; }
}
Edit:
EF is not able to map multiple tables to the same entity this way and it also doesn't make any sense because single node can be from in some cases and to in other cases.
Edit2:
Ok. This should be possible but you will have to maintain each relation separately. You must use fluent API to map this. In your context override OnModelCreating
method:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Node>()
.HasMany(n => n.Froms)
.WithMany()
.Map(m => m.ToTable("Froms"));
modelBuilder.Entity<Node>()
.HasMany(n => n.Tos)
.WithMany()
.Map(m => m.ToTable("Tos"));
}