如何在不更改模型的情况下使用Fluent API进行一对多声明? [英] How to declare one-to-many using Fluent API without changing the model?

查看:105
本文介绍了如何在不更改模型的情况下使用Fluent API进行一对多声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两节课.

class Donkey
{
  public Guid Id { get; set; }
}

class Monkey
{
  public Guid Id { get; set; }
  public Donkey Donkey { get; set; }  
}

现在,我想配置架构,以便在数据库中设置该关系.使用Fluent API,我将执行以下操作.

Now I want to configure the schema so that the relation is set in the database. Using Fluent API, I'll go something like this.

protected override void OnModelCreating(DbModelBuilder model)
{
  base.OnModelCreating(model);
  model.HasDefaultSchema("dbo");
  ...
  model.Entity<Monkey>
    .HasRequired(_ => _.Donkey)
    .WithMany(_ => _.Monkeys)
    .Map(_ => _.MapKey("DonkeyId"));
}

问题在于,现在我必须声明驴中的猴子列表.而且我不想那样做.我仍然希望猴子使用外键指向驴,所以不会只需要状态,因为我需要指定我的自定义列名称,以将指向PK的FK存储在驴表中.

The problem is that now I have to declare a list of monkeys in the donkey. And I don't want to do that. I still want the monkey to point to a donkey using foreign key, so only required status won't do, because I need to specify my custom column name to store the FK pointing to the PK in the table of donkeys.

model.Entity<Monkey>.HasRequired(_ => _.Donkey);

因此,以上代码缺少映射(当我添加它时,它不会编译).有没有解决方法,而无需实际更改 Donkey 类的定义?

So, the above lacks the mapping (and it doesn't compile when I just add it). Is there a way to work around it without actually changing the definition of Donkey class?

推荐答案

modelBuilder.Entity<Monkey>()
            .HasRequired(x => x.Donkey)
            .WithMany();

这篇关于如何在不更改模型的情况下使用Fluent API进行一对多声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆