2

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.

5
  • why can't you handle M:M ? what did you mean by self-referencing (same table name) Commented Oct 18, 2016 at 16:23
  • 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/entity Commented Oct 19, 2016 at 8:48
  • 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 ? Commented Oct 19, 2016 at 8:50
  • 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 same Commented Oct 19, 2016 at 8:53
  • can you put the code of your models ? Commented Oct 19, 2016 at 9:53

1 Answer 1

1

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);**
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.