Search code examples
c#entity-frameworkmany-to-many

Get entity by id of sub-class (many-to-many relationship)


Entities Topic and Users have a many-to-many relationship. The "table in the middle" is used for a subscription functionality, a User can subscribe to multiple Topics.

I'm trying to check if an User is subscribed to some Topic or not. If null is returned, then it means that the User is not subscribed to the Topic.

This is the structure:

Topic.Id = topicId
Topic.Users.FirstOrDefault().Id = userId

I tried this:

context
.Topics
.Where(t => t.Id == topicId && t.Users.FirstOrDefault().Id == userId).FirstOrDefault();

The problem is causing this part t.Users.FirstOrDefault() i think... If multiple users are subscribed to the same Topic, then it's working only for one User. It would have to check all Topic.Users and not just the FirstOrDefault().


Solution

  • using (var ctx = new TestContext())
    {
        var isSubscribed = ctx.Topics.Any(topic => topic.ID == topicId 
                                           && topic.Users.Any(user => user.Id == userId));
    }