ThePerplexedOne
ThePerplexedOne

Reputation: 2950

How would I go about creating this many-to-many relationship in EF Core?

So, I have the following 3 classes:

User.cs

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }

    public virtual Timezone Timezone { get; set; }
    public virtual ICollection<UserChannel> UserChannels { get; set; }
}

Channel.cs

public class Channel
{
    public int Id { get; set; }
    [Column("Channel")]
    public string Name { get; set; }
}

UserChannel.cs

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

    public virtual User User { get; set; }
    public virtual Channel Channel { get; set; }
}

UserChannel is the medium between User and Channel.

The UserChannels table looks like this:

+----+--------+-----------+
| Id | UserId | ChannelId |
+----+--------+-----------+

Both UserId and ChannelId are foreign keys, for the User and Channel class.

Now, to get which Channels belong to a user, I would have to write something like this:

using var context = new TwitchContext();
var me = context.Users.FirstOrDefault(x => x.Id == 1);
var myChannels = me.UserChannels.Select(x => x.Channel);

Is there a way I can just get a collection of Channel directly instead of using UserChannel?

Upvotes: 2

Views: 75

Answers (2)

janw
janw

Reputation: 9606

In EF.Core, many-to-many without a join table is not yet supported. So you will need to rely on the solution with the UserChannel class and the Select call for now.

As your example does not explicitly specify that a channel can have multiple users, a one-to-many solution with a ICollection<Channel> property might work as well.

Upvotes: 2

Claudio Valerio
Claudio Valerio

Reputation: 2342

Many to many relationship without referencing the join table / entity won't be available until EF Core 5 comes out, as per current roadmap:

https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/plan#many-to-many-navigation-properties-aka-skip-navigations

Feature request is tracked by this issue:

https://github.com/dotnet/efcore/issues/19003

that is included in EF Core 5.0.0 milestone.

EF Core 5 release is planned for November 2020.

Upvotes: 3

Related Questions