0

I have a class, like so

public MyObject {
    public long Id { get; set; }
    public string Name {get; set; }
}

I would like to setup a link between this class and another object of the same type. So i need another object to handle the many-to-many relationship, which is fine, something like this

public MyRelationship {
    public long Id { get; set; }
    public string Name { get; set; }
}

But how do i configure the rest. I have tried examples online, but they are too different objects.

I have tried adding to navigation properties to MyRelationship for the link, like so

public MyRelationship {
    public long Id { get; set; }
    public string Name { get; set; }

    public MyObject Parent { get; set; }
    public MyObject Child { get; set; }
}

And also 2 collections to MyObject, like so

public MyObject {
    public long Id { get; set; }
    public string Name {get; set; }

    public virtual ICollection<MyRelationship> ParentRelationships { get; set; }

    public virtual ICollection<MyRelationship> ChildRelationships { get; set; }
}

Then in my configuration file i have added

// relationships
this.HasMany(e => e.ParentRelationships)
    .WithRequired(e => e.Parent)
    .HasForeignKey(e => e.ParentId)
    .WillCascadeOnDelete(false);

this.HasMany(e => e.ChildRelationships)
    .WithRequired(e => e.Child)
    .HasForeignKey(e => e.ChildId)
    .WillCascadeOnDelete(false);

But i get errors, like this

he navigation property 'ChildRelationships' declared on type 'MyObject' has been configured with conflicting foreign keys.

Gillardo
  • 9,518
  • 18
  • 73
  • 141
  • Does [Configure Many-to-Many relationship](http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx) help? Just treat `Course` as if it was `Student` again. The inbetween table should be created automatically (you don't have to build your own class for it). – Corak Nov 24 '14 at 14:11
  • but i want to add a other property called Name to the joining class – Gillardo Nov 24 '14 at 14:11
  • If you *want* to have your own inbetween class, then you don't have a many-to-many, but two (separate) one-to-many. `MyObject` to many `MyRelationship` and `MyRelationship` to many `MyObject`. – Corak Nov 24 '14 at 14:14
  • @user2736022 Read the answer for this SO post http://stackoverflow.com/questions/7289160/ef-code-first-additional-column-in-join-table-for-ordering-purposes – Paul Zahra Nov 24 '14 at 14:26

1 Answers1

0

Why don't you just do this?

public MyObject{
    public long Id { get; set; }
    public string Name { get; set; }

    public ICollection<MyObject> Parents { get; set; }
    public ICollection<MyObject> Children { get; set; }
}
Roy Dictus
  • 32,551
  • 8
  • 60
  • 76