首页 > 解决方案 > 扩展 Asp Net Core 身份关系

问题描述

在 Asp net core (3.1) Identity 中,我想在用户和 TourOperators 之间添加多对多关系。(这个概念是许多用户可以跟随许多旅行社)。

我有旅行社类:

public class TourOperator
{
   public int Id { get; set; }
   public ICollection<Follow> Follows { get; set; }
}

我扩展了 UserIdentity 类:

public class ApplicationUser: IdentityUser
{
    public ICollection<Follow> Follow { get; set; }
}

我有关注类:

public class Follow
{
    public long Id { get; set; }

    public string UserId { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
    
    public int TourOperatorId { get; set; }
    public TourOperator TourOperator{ get; set; }
}

执行迁移后,为什么在 Follow 表中我有 4 个字段而不是 3 个?我有以下领域: 在此处输入图像描述

我认为 ApplicationUserId 不能存在

标签: asp.net-coreentity-framework-coreasp.net-identity

解决方案


Entity Framework 没有办法链接UserIdApplicationUser属性。因此,您要么需要遵循约定,因此 EF 可以做出有根据的猜测。最简单的选择是重命名您的string属性:

public string ApplicationUserId { get; set; }

或者,您可以配置它,例如使用属性:

[ForeignKey("ApplicationUser"]
public string UserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }

或者在OnModelCreating方法中,例如:

modelBuilder.Entity<Follow>()
    .WithOne(f => f.ApplicationUser)
    .HasForeignKey("UserId");

推荐阅读