c# - 我将如何在 EF Core 中创建这种多对多关系?

标签 c# entity-framework-core

所以,我有以下 3 个类(class):

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; }
}

UserChannelUserChannel 之间的媒介。

UserChannels 表如下所示:

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

UserIdChannelId 都是 UserChannel 类的外键。

现在,要获取哪些 channel 属于用户,我必须编写如下内容:

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

有没有办法可以直接获取 Channel 集合,而不是使用 UserChannel

最佳答案

根据当前路线图,在 EF Core 5 发布之前,不引用联接表/实体的多对多关系将不可用:

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

此问题跟踪功能请求:

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

它包含在 EF Core 5.0.0 里程碑中。

EF Core 5 计划于 2020 年 11 月发布。

关于c# - 我将如何在 EF Core 中创建这种多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60340064/

相关文章:

asp.net-core - 使用 Entity Framework 通过 ID 从其他表中获取值

c# - 在 EF Core 中执行两个相关操作

c# - 复杂类型字段

c# - 使用带有 sas token 的 Rest api 更新表存储实体显示 "method not allowed"

c# - 删除被调用的查询异常 C#

entity-framework - SQL 超时已过期。操作完成前超时时间已过或服务器未响应

c# - 为什么 "IQueryable.Where()"在此查询中提供与 "IEnumerable.Where()"不同的结果?

asp.net - 添加标签来讨论 Entity Framework 中的多对多关系

游戏开发中的 C# 与 Java

c# - 用于 PostSharp 2.0 和 .NET Framework 2.0 的 Log4PostSharp