[英]How would I go about creating this many-to-many relationship in EF Core?
So, I have the following 3 classes:所以,我有以下3个类:
User.cs用户.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频道.cs
public class Channel
{
public int Id { get; set; }
[Column("Channel")]
public string Name { get; set; }
}
UserChannel.cs用户频道.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
. UserChannel
是User
和Channel
之间的媒介。
The UserChannels
table looks like this: UserChannels
表如下所示:
+----+--------+-----------+
| Id | UserId | ChannelId |
+----+--------+-----------+
Both UserId
and ChannelId
are foreign keys, for the User
and Channel
class. UserId
和ChannelId
都是外键,用于User
和Channel
类。
Now, to get which Channels
belong to a user, I would have to write something like this:现在,要获取哪些Channels
属于用户,我必须这样写:
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
?有没有办法可以直接获取Channel
集合而不是使用UserChannel
?
Many to many relationship without referencing the join table / entity won't be available until EF Core 5 comes out, as per current roadmap:根据当前路线图,在 EF Core 5 出现之前,不引用连接表/实体的多对多关系将不可用:
https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/plan#many-to-many-navigation-properties-aka-skip-navigations 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 https://github.com/dotnet/efcore/issues/19003
that is included in EF Core 5.0.0 milestone.包含在 EF Core 5.0.0 里程碑中。
EF Core 5 release is planned for November 2020. EF Core 5 版本计划于 2020 年 11 月发布。
In EF.Core, many-to-many without a join table is not yet supported .在 EF.Core 中,尚不支持没有连接表的多对多。 So you will need to rely on the solution with the UserChannel
class and the Select
call for now.因此,您现在需要依靠UserChannel
类和Select
调用的解决方案。
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.由于您的示例没有明确指定一个频道可以有多个用户,因此具有ICollection<Channel>
属性的一对多解决方案也可能适用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.