MCoder
MCoder

Reputation: 39

Self-referencing many to many relation in Entity Framework Core

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:

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.

Upvotes: 2

Views: 2140

Answers (1)

AymanAussieFromEgypt
AymanAussieFromEgypt

Reputation: 11

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);**

Upvotes: 1

Related Questions