实体框架从对象创建列

Entity Famework creates columns from objects

我在尝试与用户建立关系时遇到了问题。一个用户可以是另一个用户的营养师,所以我有这样的结构:

public class ApplicationUser : IdentityUser
{
        [ForeignKey("MenteeId")]
        public virtual ICollection<MenteesDieticians> Dieticians { get; set; }

        [ForeignKey("DieticianId")]
        public virtual ICollection<MenteesDieticians> DieticianMentees { get; set; }
}

public class MenteesDieticians
{
        [Key]
        public int MenteesDieticiansId { get; set; }

        [Required]
        [ForeignKey("Mentee")]
        public string MenteeId { get; set; }

        [ForeignKey("MenteeId")]
        public virtual ApplicationUser Mentee { get; set; }

        [Required]
        [ForeignKey("Dietician")]
        public string DieticianId { get; set; }

        [ForeignKey("DieticianId")]
        public virtual ApplicationUser Dietician { get; set; }
}

也在我的 DbContext 中 class 我正在定义关系:

protected override void OnModelCreating(ModelBuilder builder)
{
        base.OnModelCreating(builder);

        builder.Entity<ApplicationUser>()
            .HasMany(x => x.DieticianMentees)
            .WithOne()
            .HasForeignKey(x => x.DieticianId);
        builder.Entity<ApplicationUser>()
            .HasMany(x => x.Dieticians)
            .WithOne()
            .HasForeignKey(x => x.MenteeId);

        builder.Entity<MenteesDieticians>()
            .HasOne(x => x.Mentee)
            .WithOne()
            .HasForeignKey<MenteesDieticians>(t => t.MenteeId);
        builder.Entity<MenteesDieticians>()
            .HasOne(x => x.Dietician)
            .WithOne()
            .HasForeignKey<MenteesDieticians>(t => t.DieticianId);
}

最后,我的迁移代码如下所示:

    migrationBuilder.CreateTable(
        name: "MenteesDieticians",
        columns: table => new
        {
            MenteesDieticiansId = table.Column<int>(nullable: false)
                .Annotation("MySQL:ValueGenerationStrategy", MySQLValueGenerationStrategy.IdentityColumn),
            MenteeId = table.Column<string>(nullable: false),
            DieticianId = table.Column<string>(nullable: false),
            ApplicationUserId = table.Column<string>(nullable: true),
            ApplicationUserId1 = table.Column<string>(nullable: true)
        },

为什么我有那些 ApplicationUserId 和 ApplicationUserId1 列?如何解决?

您如何看待这样定义这些关系?老实说,我需要用户只有一个营养师,但我没有找到实现它的方法。

尝试以下配置。首先,仅从一侧进行配置就足够了。其次,从模型中删除注释。

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<ApplicationUser>()
        .HasMany(x => x.Dieticians)
        .WithOne(x => x.Dietician)
        .HasForeignKey(x => x.DieticianId);
    builder.Entity<ApplicationUser>()
        .HasMany(x => x.DieticianMentees)
        .WithOne(x => x.Mentee)
        .HasForeignKey(x => x.MenteeId);
}

我不得不说,你这里的设置有点奇怪。您能否详细说明您的目标是什么?