EF Code First : Linking on non-key property in configuration

I'm looking to perform a seemingly difficult EF Code First relationship between some of my entities. I've searched all around Stack Overflow as well as the web but can't seem to come up with anything. I have a simple class outlined below. The PK for a Program is its Id. It also has a (non-PK) FamilyId value. There is no "Families" table or anything similar. Moreover, "FamilyId" is not a FK to the Id value of a different Program entity. In my mind, I consider it a "grouping" of sorts.

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

    public virtual List<Program> RelatedPrograms { get; set; }
    public int? FamilyId { get; set; }

Let me explain further with some sample data.

Id : 1, FamilyId : 17 Id : 2, FamilyId : 17 Id : 3, FamilyId : 18 Id : 4, FamilyId : 17

Using EF Code First in my configuration I'd like to add logic that would populate the "RelatedPrograms" property with Program 1, 2, and 4 if I do a query for any of those three (e.g. the point here is that they are all related to each other through this arbitray property). If I query for Program 3, there'd only be 1 record in the RelatedPrograms property and it would be Program 3 since nothing else shares that same FamilyId.

I think my logic needs to be similar to the following except that the following automatically makes references to the Id column behind the scenes; I need my linking to solely be based upon the FamilyId column of the Program being accessed and the FamilyId value of the other Programs in the database.

this.HasMany(p => p.RelatedPrograms).WithRequired().HasForeignKey(p => p.FamilyId);

Any help you could provide on this would be appreciated.



If I am getting this right, you just want to know a group of Programs based on an attribute, the family ID? This sounds to me not so much as a property of the Program object, but a group of programs. I would just have the Program Id and Family Id (which sounds more like a category to me) in the Program entity, and when you need to know the related programs, you just query the entity:

var relatedPrograms = context.Programs.Where(p => p.FamilyId == myFamilyId).ToList();

Need Your Help

Query the web Api with OData

entity-framework odata code-first web-api

I have a web api which has a method to get products. The products belong to a category. Now to get to the problem, when i call the api, it returns a json object of the products but the products don...

Passing member function pointer to the c-style function

c++ c pointers c++11 callback

I am trying to pass member function pointer to the c-style function (as it's lib in C)