具有可选子导航属性的Entity Framework会创建额外的列

时间:2014-02-12 00:45:41

标签: entity-framework

我刚刚注意到一个相当奇怪的行为,当你的模型的父模型有一个子列表时,实体框架如何创建一个代码优先数据库,同时也是一个特定子项的可选导航属性:我结束了在孩子身上有一个额外的可以为空的外键列,我没想到。有人可以解释一下这个专栏是否真的有必要吗?就此而言,任何人都可以建议一种更好的方式来表明特定的孩子是选定/活跃的。

详细说明:

鉴于此模型:

public class Parent
{
    public int Id { get; set; }

    public virtual List<Child> Children { get; set; }

    // Optional navigation property to one of the child objects.
    public int? ActiveChildId { get; set; }
    public virtual Child ActiveChild { get; set; }
}

public class Child
{
    public int Id { get; set; }

    public int ParentId { get; set; }
    public virtual Parent Parent { get; set; }
}

我最终得到以下数据库:

CREATE TABLE [dbo].[Parents](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ActiveChildId] [int] NULL,
 CONSTRAINT [PK_dbo.Parents] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Parents]  WITH CHECK ADD  CONSTRAINT [FK_dbo.Parents_dbo.Children_ActiveChildId] FOREIGN KEY([ActiveChildId])
REFERENCES [dbo].[Children] ([Id])
GO

ALTER TABLE [dbo].[Parents] CHECK CONSTRAINT [FK_dbo.Parents_dbo.Children_ActiveChildId]
GO

CREATE TABLE [dbo].[Children](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ParentId] [int] NOT NULL,
    [Parent_Id] [int] NULL,
 CONSTRAINT [PK_dbo.Children] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Children]  WITH CHECK ADD  CONSTRAINT [FK_dbo.Children_dbo.Parents_Parent_Id] FOREIGN KEY([Parent_Id])
REFERENCES [dbo].[Parents] ([Id])
GO

ALTER TABLE [dbo].[Children] CHECK CONSTRAINT [FK_dbo.Children_dbo.Parents_Parent_Id]
GO

ALTER TABLE [dbo].[Children]  WITH CHECK ADD  CONSTRAINT [FK_dbo.Children_dbo.Parents_ParentId] FOREIGN KEY([ParentId])
REFERENCES [dbo].[Parents] ([Id])
GO

ALTER TABLE [dbo].[Children] CHECK CONSTRAINT [FK_dbo.Children_dbo.Parents_ParentId]
GO

即。子项上有ParentId(NOT NULL)列,子项上有Parent_Id(NULL)列。

在我看来,既然我们已经有1:N的外键关系父母对孩子,那么通过添加单向1:[0或1] Parent to Child关系,它不应该创建另一个外国人孩子的关键栏目。

1 个答案:

答案 0 :(得分:4)

添加InverseProperty属性:

public class Child
{
    public int Id { get; set; }

    public int ParentId { get; set; }

    [InverseProperty( "Children" )]
    public virtual Parent Parent { get; set; }
}

或通过Fluent API映射关系,并将FK指定为ParentId

        modelBuilder.Entity<Parent>()
            .HasMany( p => p.Children )
            .WithRequired( c => c.Parent )
            .HasForeignKey( c => c.ParentId );