How to declare one-to-many using Fluent API without changing the model?

ぃ、小莉子 提交于 2019-12-13 06:12:10

问题


I have two classes as follows.

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

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

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"));
}

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);

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?


回答1:


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


来源:https://stackoverflow.com/questions/36520955/how-to-declare-one-to-many-using-fluent-api-without-changing-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!