Creating the relationship between many and many relationships in Entity Framework 7

I am trying to customize my database using the free Entity Framework 7 API to add a many-to-many binding. The class in question is as follows:

public class Definition { // Some properties public virtual ICollection<Definition> AllowedChildDefinitions { get; set; } } 

where the alleged relationship is that each definition can have an arbitrary number of children of any instance. I expect a separate table with parent / child columns, where each parent can have multiple children, and each child can have multiple parents.

There are many to many examples and examples of self-regulation tables, but I cannot figure out how to combine them.

+7
c # asp.net-core entity-framework entity-framework-core
source share
2 answers

The workaround is to map the connection table to the entity. Please study this.

 public class Definition { public int Id { get; set; } public ICollection<ChildrenDefinition> ChildrenDefinitions{ get; set; } } public class ChildrenDefinition { public int DefinitionId { get; set; } public Definition Definition { get; set; } public int ChildrenId { get; set; } public Children Children { get; set; } } public class Children { public int Id { get; set; } public ICollection<ChildrenDefinition> ChildrenDefinitions{ get; set; } } 

Be sure to configure the child definition using the compound key:

 protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<ChildrenDefinition>().HasKey(x => new { x.DefinitionId, x.ChildrenId }); } 

To navigate, use Select:

 // Children.Definition var definitions = Children.ChildrenDefinitions.Select(c => c.Definition); 

Hope this helps you!

0
source share

Say, for example, you have the following two classes.

 1. Definition 2. Children 

For many, many relationship relationships, you have to put the class of the parent class ICollection in the child class and put the ICollection of the child class in the parent class, as shown below.

 public class Definition { // Some properties public virtual ICollection<Children> Childrens { get; set; } } 

another class (children) must have the ICollection of Definition class.

  public class Children { // Some properties public virtual ICollection<Definition> Definitions { get; set; } } 

In the DataContext, you must create a mapping for the new table, as shown below,

  protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Definition>() .HasMany(l => l.Childrens) .WithMany(o => o.Definitions) .Map(m => { m.MapLeftKey("DefinitionId"); m.MapRightKey("ChildrenId"); m.ToTable("ChildrenDefinitions"); }); } 

Note. You will have a separate table created using two columns (DefinitionId, ChildrenId). And this table (ChildrenDefinitions) will allow you to create a many-to-many relationship with the definition class and the children class.

Hope this helps you!

-one
source share

All Articles