2
votes

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
why can't you handle M:M ? what did you mean by self-referencing (same table name)Sampath
I haven't found an way to do that with EF core so far. With self-referencing (same table name) I mean that both entities in the realtion (Company) are the same table/model/entityMCoder
do you need to know how to handle M : M with EF core or else ? you must provide more info.Otherwise how can we help to you ? what are your models code ?Sampath
I know how to handle a m:m relation. In the case of self-referencing my method doesn't work because the entities are the sameMCoder
can you put the code of your models ?Sampath

1 Answers

1
votes

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