mysql - 自引用 MVC5 EF6 在数据库中创建新 ID

标签 mysql asp.net-mvc entity-framework self-reference

我正在 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?有人可以指导我做错了什么吗?

最佳答案

OnModelCreatingDbContext 的一种方法。您不能将其添加到任何实体类中。换句话说,您的流畅配置从未真正运行,因此您的设置不会应用于数据库。

在您的上下文中重写 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/

相关文章:

php - 一段时间内多个数组

mysql - 无法在 mysql 5.5.47-cll 中使用 Current_timestamp 作为默认值

c# - MVC - 具有多个选择列表的 Controller

c# - 当触发 Masstransit 消费者时启动新的 LifetimeScope

entity-framework - IdentityUserLogin<string>' 需要在添加迁移时定义主键错误

mySQL试图用约束外键创建表

c# - 在 MVC3 问题中键入安全的 URL 操作

javascript - 在表格中单击按钮时读取输入文本值

entity-framework - EF Code First 删除数据库?

mysql - 如何计算平均值?