背景:我试图让我的 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; }
}
这会产生:
create table [dbo].[Groups] (
[Id] [int] not null identity,
primary key ([Id])
);
create table [dbo].[People] (
[Id] [int] not null identity,
[GroupId] [int] null,
primary key ([Id])
);
alter table [dbo].[People] add constraint [Person_Group] foreign key ([GroupId]) references [dbo].[Groups]([Id]);
完美的。
但是将其移至 OnModelCreating (或等效的 EntityTypeConfiguration 代码),如下所示:
modelBuilder.Entity<Person>()
.HasOptional(t => t.Group)
.WithMany()
.HasForeignKey(t => t.GroupId);
结果是这样的(对于新的或迁移的数据库):
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]);
为什么要创建 Group_Id 而为什么不使用 GroupId?
谢谢!