Entity framework [ForeignKey]属性与模型创建或EntityTypeConfiguration的不同结果

Entity framework [ForeignKey]属性与模型创建或EntityTypeConfiguration的不同结果,entity-framework,entity-framework-5,entity-framework-6,Entity Framework,Entity Framework 5,Entity Framework 6,背景:我试图使我的EF POCO不受对EF的引用的影响,因此所有模型配置代码都将进入OnModelCreating或EntityTypeConfiguration类,而不是使用属性(从而避免对System.ComponentModel.DataAnnotations.Schema的引用)。问题在于,当属性未建立外键时,在构建模型时,外键似乎会被忽略。下面是一个例子: public class Person { public int Id { get; set; } [Foreig

背景:我试图使我的EF POCO不受对EF的引用的影响,因此所有模型配置代码都将进入OnModelCreating或EntityTypeConfiguration类,而不是使用属性(从而避免对System.ComponentModel.DataAnnotations.Schema的引用)。问题在于,当属性未建立外键时,在构建模型时,外键似乎会被忽略。下面是一个例子:

public class Person
{
    public int Id { get; set; }
    [ForeignKey("Group")]
    public int? GroupId { get; set; }
    public Group Group { get; set; }
}
public class Group
{
    public int Id { get; set; }
    public List<Person> People { get; set; }
}
public class Context : DbContext
{
    public DbSet<Group> Groups { get; set; }
    public DbSet<Person> People { get; set; }
}
太好了

但将其移动到OnModelCreating(或等效EntityTypeConfiguration代码),如下所示:

modelBuilder.Entity<Person>()
    .HasOptional(t => t.Group)
    .WithMany()
    .HasForeignKey(t => t.GroupId);
为什么要创建组Id,为什么不使用组Id


谢谢

看起来您的映射是错误的

由于您在
组中有一个导航属性
,因此需要将其包含在映射中,如下所示:

modelBuilder.Entity<Person>()
    .HasOptional(t => t.Group)
    .WithMany(t => t.People) // <---
    .HasForeignKey(t => t.GroupId);
modelBuilder.Entity()
.has可选(t=>t.Group)
.WithMany(t=>t.People)//t.GroupId);

否则,EF将为两个实体之间的不同关系使用navigation属性并创建另一个外键。

我应该指出,我知道在这种情况下不使用属性或fluent API是可行的,因为EF足够聪明,可以选择GroupId作为FK。但这不是重点。首先,因为如果它是GroupFK而不是GroupId(至少在不调整约定的情况下),那就不是真的。第二,更重要的是,我想理解为什么它在这个案例中会做出这种区分,特别是因为它足够聪明,可以在所有其他案例中都能找到它。看起来我可能标记得太快了。是的,这在OnModelCreating中确实有效,但我只是将其放入EntityTypeConfiguration类中,它失败了。与上述问题相同,添加了患者Id。@Ryan-听起来不太可能-您确定EntityTypeConfiguration已连接到OnModelCreating方法中吗?
create table [dbo].[Groups] (***same as above***);
create table [dbo].[People] (
    [Id] [int] not null identity,
    [GroupId] [int] null,
    [Group_Id] [int] null,
    primary key ([Id])
);
alter table [dbo].[People] add constraint [Group_People] foreign key ([Group_Id]) references [dbo].[Groups]([Id]);
alter table [dbo].[People] add constraint [Person_Group] foreign key ([GroupId]) references [dbo].[Groups]([Id]);
modelBuilder.Entity<Person>()
    .HasOptional(t => t.Group)
    .WithMany(t => t.People) // <---
    .HasForeignKey(t => t.GroupId);