Search code examples
mysqlasp.net-mvcentity-frameworkself-reference

Self Referencing MVC5 EF6 creating a new Id in database


I am creating a self referenciing model in an MVC5 Model which is an after thought. The model is as below:

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);

        }
 }

This creates a new Id field in MYSQL database as GalleryCatParent_GalleryCatId instead of GalleryCatParentId? Can someone guide what I am doing wrongly?


Solution

  • OnModelCreating is a method of DbContext. You can't just add it to any entity class. In other words, your fluent config is never actually being run, so your setup is not being applied to the database.

    Either override OnModelCreating in your context and add this fluent config there, or if you want to keep the config with the entity, you can do that via:

    public class GalleryCat
    {
        ...
    
        public class Config : EntityTypeConfiguration<GalleryCat>
        {
            public Config()
            {
                HasOptional(c => c.GalleryCatParent)
                    .WithMany(c => c.Children)
                    .HasForeignKey(p => p.GalleryCatParentId);
            }
        }
    }
    

    Then, override OnModelCreating in your context like so:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new GalleryCat.Config());
    }