2

Let's say I have the following two models:

Person             N
Subscription       N

They are in a many-to-many relationship (Each Person can have multiple Subscriptions, and each Subscription can have multiple Persons), so Entity Framework creates a cross reference table:

PersonSubscriptions:  PersonId  |  SubscriptionId

If I wanted to record when each person started subscribing, it would make the most sense to have a Date column in the cross reference table:

PersonSubscriptions:  PersonId  |  SubscriptionId  |  SubscribedOn

How can I achieve this with Entity Framework and how would I query, say, to get all Persons that subscribed after day X to a given Subscription?

1 Answer 1

3

In this situation, you no longer have a many-to-many relationship in a traditional sense, you instead have 2 distinct 1 to many relationships with a 3rd entity. In essence, you will have 3 classes to work with:

public class Person 
{
    public int PersonId { get; set; }
    public virtual IEnumerable<SubscriptionInfo> SubscriptionInfos { get; set; }
}

public class Subscription 
{
    public int SubscriptionId { get; set; }
    public virtual IEnumerable<SubscriptionInfo> SubscriptionInfos { get; set; }
}

public class SubscriptionInfo 
{
    public int PersonId { get; set; }
    public int SubscriptionId { get; set; }
    public DateTime SubscribedOn { get; set; }

    [RelatedTo(ForeignKey="PersonId")]
    Public virtual Person Person { get; set; }

    [RelatedTo(ForeignKey="SubscriptionId")]
    Public virtual Subscription Subscription { get; set; }
}

var db = new PeopleSubscribedEntities();
var subscription = db.Subscriptions.Find(1);
var people = subscription.SubscriptionInfos
                         .Select(si => si.Person 
                                       && si => si.SubscribedOn > someDate);

If Entity Framework were to treat this table as a many to many, you would lose the extra attributes.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Andrew! Would you expect your sample code to create the table as I outlined in my question? Or a separate SubscriptionInfo table?
I just referred to it as SubscriptionInfo in my samples, but if it were named PersonSubscriptions, it would create a table named that, with the 3 fields... I was mostly offering a direction to take the code, but the names can be changed, of course. With the class names I used, Entity Framework would create a SubscriptionInfo table instead of the default join table.

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.