Entity Framewrok Code First: Can not rename FK in optional 1:1 relationship

93 views Asked by At

Consider the following Parent/Child model:

public class Parent
{
   public int Id { get; set; }    
   public virtual Child MyChild { get; set; }
}
public class Child
{
   public int Id { get; set; }        

   public int? PId { get; set; }
   [ForeignKey("PId")]
   public virtual Parent MyParent { get; set; }
}

and the context:

class Context : DbContext
{
        public DbSet<One_To_One.Case1.Child> Child { get; set; }
        public DbSet<One_To_One.Case1.Parent> Parent { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Parent>()
                .HasOptional(p => p.MyChild)
                .WithOptionalPrincipal(p => p.MyParent);
        }
}

It generates this table schema:

CREATE TABLE [dbo].[Children] (
    [Id]          INT IDENTITY (1, 1) NOT NULL,
    [MyParent_Id] INT NULL,
    CONSTRAINT [PK_dbo.Children] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_dbo.Children_dbo.Parents_MyParent_Id] FOREIGN KEY ([MyParent_Id]) REFERENCES [dbo].[Parents] ([Id])
);

CREATE TABLE [dbo].[Parents] ([Id] INT IDENTITY (1, 1) NOT NULL);

While Database is generated with expected schema, I am surprised why the foreign key in Children table is not PId. Any help?

0

There are 0 answers