0

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?

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

1 Answers1

2

You can use HasOptional:

  model.Entity<Monkey>
    .HasOptional(_ => _.Donkey)
    .WithMany()
    .Map(_ => _.MapKey("DonkeyId"));
Vano Maisuradze
  • 5,829
  • 6
  • 45
  • 73