0

I have some entities that can be associated with each other. A simple pair of classes to do this would ideally look like:

public class linkableEntity
{
    public int Id { get; set;} 

    public virtual ICollection<Link> Links { get; set; }
}

public class Link
{
    public int Id { get; set; }

    public int SomeProperty { get; set; }

    public int entity1Id { get; set; }
    public virtual LinkableEntity entity1 { get; set;}

    public int entity2Id { get; set; }
    public virtual LinkableEntity entity2 { get; set;}
}

With tables something like:

Table linkableEntity
Column Id

Table link
Column entityId1 - foreign key to linkableEntity.Id
Column entityId2 - foreign key to linkableEntity.Id
Column someProperty

Having tried this out, and looking at this question: Entity Framework Code First - two Foreign Keys from same table I don't think that what I want to do was possible in EF4, has anything changed in EF6 that would make this possible? (I haven't found any more recent questions addressing this subject)

If not, is there a better way of representing this than changing linkableEntity to something like:

public class linkableEntity
{
    public int Id { get; set;} 

    public virtual ICollection<Link> LinksWhereFirst { get; set; }
    public virtual ICollection<Link> LinksWhereSecond { get; set; }
}

and then dealing with the mess?

Community
  • 1
  • 1
Dan
  • 7,446
  • 6
  • 32
  • 46
  • I'm pretty sure I have one of those in project I'm working on. Did you try and see if it works and ran into a problem or are you just asking so other people will test it for you? – kjbartel Mar 02 '15 at 15:33
  • Yes, I did try it - although I may have got something wrong. The migration EF generated for the model included an extra foreign key indicating it didn't understand what I was trying to do. At which point I went searching and found the question I mentioned above. If you have something like this working then I'd be glad to see it. – Dan Mar 02 '15 at 15:36
  • I don't have the code with me to check but I'm pretty sure the only thing I've used is mappings. I'm assuming that the `entity1Id` is the same as the id of the `linkableEntity` and thus the 'Links' collection contains a list of `Link` objects all having that same id as the `entity1Id`? If you want the list to contain `Link` objects which have the id as either `entity1Id` or `entity2Id` then you're out of luck. – kjbartel Mar 02 '15 at 15:44
  • I do want the collection to contain Link objects which have the id as either entity1Id or entity2Id :( – Dan Mar 02 '15 at 15:57
  • 1
    Then no it won't work. You could make the two collections protected though and have another public collection which wraps the other two. – kjbartel Mar 02 '15 at 16:02

0 Answers0