实体Framewrok代码优先:无法以可选的1:1关系重命名FK

时间:2015-06-10 15:53:15

标签: c# entity-framework ef-code-first

考虑以下父/子模型:

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

和上下文:

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

它生成此表模式:

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

虽然使用预期的架构生成数据库,但我很惊讶为什么Children表中的外键不是PId。有什么帮助吗?

0 个答案:

没有答案