【问题标题】:Net Core ApplicationUser with foreign key to itself具有自身外键的 Net Core ApplicationUser
【发布时间】:2019-07-23 14:35:11
【问题描述】:

我正在使用 Net Core 2.2 和实体框架。我有一个 ApplicationUser 类,用于多种用户类型,外键相互连接,但实体框架在添加迁移时出错:

Unable to determine the relationship represented by navigation property 'ApplicationUser.Class' of type 'Class'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

我不确定实现此功能的正确方法是什么。谁能帮我?

我的 ApplicationUser 类:

public class ApplicationUser : IdentityUser
{
    public string CustomerId { get; set; }
    public string TeacherId { get; set; }
    public int? ClassId { get; set; }
    public int? SettingsId { get; set; }

    public virtual ApplicationUser Customer { get; set; }
    public virtual ApplicationUser Teacher { get; set; }
    public virtual Class Class { get; set; }
    public virtual Settings Settings { get; set; }
    public virtual ICollection<Class> Classes { get; set; }
    public virtual ICollection<License> Licenses { get; set; }
    public virtual ICollection<Exercise> Exercises { get; set; }
    public virtual ICollection<GameProgress> GameProgresses { get; set; }
    public virtual ICollection<StudentExercise> StudentExercises { get; set; }
}

而且因为它在错误中,我的 Class 类:

public class Class
{
    public int Id { get; set; }
    public string TeacherId { get; set; }
    public int? SettingsId { get; set; }

    public virtual ApplicationUser Teacher { get; set; }
    public virtual Settings Setting { get; set; }
    public virtual ICollection<Exercise> Exercises { get; set; }
    public virtual ICollection<ApplicationUser> Students { get; set; }
}

【问题讨论】:

    标签: entity-framework asp.net-core


    【解决方案1】:

    这个问题与自引用ApplicationUser 关系无关。异常特别告诉您这是Class 的问题。问题是你在ApplicationUser 上有一个对Class 的引用属性,但是在Class 上,你既有ApplicationUsers (Students) 的集合,又有对@987654328 的单独引用@ (Teacher)。简而言之,EF 不知道这个外键实际指的是哪个。

    解决方案正是异常告诉您的:添加流利的配置以消除歧义:

    public override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ApplicationUser>()
            .HasOne(x => x.Class)
            .WithMany(x => x.Students);
    }
    

    【讨论】:

    • 呃,谢谢你,克里斯。一如既往,你是一个很好的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 2019-06-23
    • 1970-01-01
    相关资源
    最近更新 更多