How to declare a one-to-many in Fluent API so that it's not required?

核能气质少年 提交于 2019-12-12 02:59:00

问题


Suppose we have the two classes below.

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

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

I can configure the relation as follows.

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

I'd like to make it not-required, i.e. so that Donkey property can be null but if it isn't, it's pointing to a row in that table.

I'm not sure if it's possible because that being a FK relies on its target to be a PK, which can't be null ever. However, in C#, it'd make a perfect sense. I can have a freely running monkey with no attachments (since its donkey is null) but I also can assign a donkey to it and I want EF and navigational properties to do the fetching magic for me.

Is it possible to achieve?


回答1:


You can use HasOptional:

  model.Entity<Monkey>
    .HasOptional(_ => _.Donkey)
    .WithMany()
    .Map(_ => _.MapKey("DonkeyId"));


来源:https://stackoverflow.com/questions/36521800/how-to-declare-a-one-to-many-in-fluent-api-so-that-its-not-required

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