考虑以下父/子模型:
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
。有什么帮助吗?