如何在不更改模型的情况下使用 Fluent API 声明一对多?
How to declare one-to-many using Fluent API without changing the model?
我有两个class如下。
class Donkey
{
public Guid Id { get; set; }
}
class Monkey
{
public Guid Id { get; set; }
public Donkey Donkey { get; set; }
}
现在我想配置模式以便在数据库中设置关系。使用 Fluent API,我会这样做。
protected override void OnModelCreating(DbModelBuilder model)
{
base.OnModelCreating(model);
model.HasDefaultSchema("dbo");
...
model.Entity<Monkey>
.HasRequired(_ => _.Donkey)
.WithMany(_ => _.Monkeys)
.Map(_ => _.MapKey("DonkeyId"));
}
问题是现在我不得不声明一个驴子里的猴子列表。我不想那样做。我仍然希望猴子使用外键指向驴子,所以只有 required status 不行,因为我需要指定我的自定义列名来存储 FK 指向驴子 table 中的 PK。
model.Entity<Monkey>.HasRequired(_ => _.Donkey);
所以,上面缺少映射(当我添加它时它不会编译)。有没有办法在不实际更改 Donkey class?
的定义的情况下解决它
modelBuilder.Entity<Monkey>()
.HasRequired(x => x.Donkey)
.WithMany();
我有两个class如下。
class Donkey
{
public Guid Id { get; set; }
}
class Monkey
{
public Guid Id { get; set; }
public Donkey Donkey { get; set; }
}
现在我想配置模式以便在数据库中设置关系。使用 Fluent API,我会这样做。
protected override void OnModelCreating(DbModelBuilder model)
{
base.OnModelCreating(model);
model.HasDefaultSchema("dbo");
...
model.Entity<Monkey>
.HasRequired(_ => _.Donkey)
.WithMany(_ => _.Monkeys)
.Map(_ => _.MapKey("DonkeyId"));
}
问题是现在我不得不声明一个驴子里的猴子列表。我不想那样做。我仍然希望猴子使用外键指向驴子,所以只有 required status 不行,因为我需要指定我的自定义列名来存储 FK 指向驴子 table 中的 PK。
model.Entity<Monkey>.HasRequired(_ => _.Donkey);
所以,上面缺少映射(当我添加它时它不会编译)。有没有办法在不实际更改 Donkey class?
的定义的情况下解决它modelBuilder.Entity<Monkey>()
.HasRequired(x => x.Donkey)
.WithMany();