我正在 MVC5 模型中创建一个自引用模型,这是事后的想法。模型如下:
public class GalleryCat
{
[Key]
public int GalleryCatId { get; set; }
public string CatName {get; set;}
public virtual GalleryCat GalleryCatParent { get; set; }
public int GalleryCatParentId {get; set; }
public virtual ICollection<GalleryCat> Children { get; set; }
public virtual ICollection<Gallery> Galleries { get; set; }
protected void OnModelCreating (DbModelBuilder modelBuilder)
{
modelBuilder.Entity<GalleryCat>()
.HasOptional(c => c.GalleryCatParent)
.WithMany(c => c.Children)
.HasForeignKey(p => p.GalleryCatParentId);
}
}
这会在 MYSQL 数据库中创建一个新的 Id 字段作为 GalleryCatParent_GalleryCatId 而不是 GalleryCatParentId?有人可以指导我做错了什么吗?
最佳答案
OnModelCreating
是DbContext
的一种方法。您不能将其添加到任何实体类中。换句话说,您的流畅配置从未真正运行,因此您的设置不会应用于数据库。
在您的上下文中重写 OnModelCreating
并在其中添加此流畅的配置,或者如果您想将配置与实体一起保留,您可以通过以下方式执行此操作:
public class GalleryCat
{
...
public class Config : EntityTypeConfiguration<GalleryCat>
{
public Config()
{
HasOptional(c => c.GalleryCatParent)
.WithMany(c => c.Children)
.HasForeignKey(p => p.GalleryCatParentId);
}
}
}
然后,在您的上下文中重写 OnModelCreating
,如下所示:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new GalleryCat.Config());
}
关于mysql - 自引用 MVC5 EF6 在数据库中创建新 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42933647/