当我试图在我的用户之间创建reation时,我遇到了一个问题。一个用户可以是另一个用户的营养师,所以我有这样的结构:
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类中,我还定义了关系:
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);
}
我得说,你的设置有点奇怪。你能详细说明你在这里的目标是什么吗?