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

c# entity-framework-core

Question

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?

1
2
2/21/2020 2:16:59 PM

Accepted Answer

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://docs.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.

3
2/21/2020 2:09:46 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow