Self-referencing many to many relation in Entity Framework Core

c# entity-framework-core many-to-many self-referencing-table visual-studio-2015

Question

I'm using Entity Framework Core (EF) for building models for a project.

Now I want to save companies and their hierachy. Therefore I have following cases:

  • A subsidiary company (Child) has any number of children and any number of parents.
  • A parent company has any number of children and any number of parents, too.

The many to many reation is hardly the problem. The real problem is the combination of many to many and the self-referencing (same table name).

I have no idea how to write a model with those cases. I hope any one can help me.

1
2
10/18/2016 2:42:46 PM

Popular Answer

At The Model Class ( Passenger in my Case where multiple passengers can be related / linked to a specific one Passenger ..) Define the relationship as below :

Passenger.cs

public int? LinkedToPassengerId { get; set; }
[ForeignKey("LinkedToPassengerId")]
public virtual Passenger LinkedToPassenger { get; set; }
public virtual ICollection<Passenger> Passengers { get; set; }

Then At the DBContext Class use the following Fluent API to define the Self-Ref one to many relationship inside the OnModelCreating method:

modelBuilder.Entity<Passenger>() <BR>
    .HasMany(e => e.Passengers) <BR>
    .WithOne(e => e.LinkedToPassenger) //Each passenger points back to his parent Passenger
    .HasForeignKey(e => e.LinkedToPassengerId);

Finally from any controller method you can read the related / linked rows for any Passenger using the following LINQ:

var linkPasses = new List<Passenger>();
var Passes = _context.Passengers.Include(c => c.Passengers).Where(m => m.ID == id); 
foreach(Passenger tmpPass in Passes)
    foreach(Passenger tmpPass2 in tmpPass.Passengers) 
       linkPasses.Add(tmpPass2);**
1
4/27/2017 2:10:00 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow