【问题标题】:Extend Asp Net Core Identity Relation扩展 Asp Net Core 身份关系
【发布时间】:2021-03-21 01:03:26
【问题描述】:

在 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 不能存在

【问题讨论】:

  • 你需要告诉 EF UserId 是链接到ApplicationUser 的关键
  • 一句话:约定ApplicationUser -> ApplicationUserId

标签: asp.net-core entity-framework-core asp.net-identity


【解决方案1】:

实体框架无法链接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");

【讨论】:

    猜你喜欢
    • 2019-02-19
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    相关资源
    最近更新 更多