0

I need to declare an 0..1 to many relationship using Fluent API with EntityFramework Core. Right now I have a 1 to many relationship and I cannot figure out how to change that to a 0..1 to many.

modelBuilder.Entity<Item>()
      .HasOne(c => c.Constraint)
      .WithMany(p => p.Constraint)
      .HasForeignKey(p => p.Growid)
      .HasPrincipalKey(b => b.Growid);

Any help would be greatly appreciated.

BeebFreak
  • 111
  • 1
  • 6

1 Answers1

1

From the docs:

If you have a foreign key property in your entity class then the requiredness of the relationship is determined based on whether the foreign key property is required or optional

Further information:

A property is considered optional if it is valid for it to contain null. If null is not a valid value to be assigned to a property then it is considered to be a required property.

Therefore, in order to change the nature of the relationship from required (1 to many) to a 0 .. 1 to many, you need to make the foreign key nullable. You do that in the domain entity:

public class Item
{
    public int Item Id { get; set; }
    public string Name { get; set; }
    public int? ForeignKeyItemId { get; set; }
    public ForeignKeyItem ForeignKeyItem { get; set; }
}
Mike Brind
  • 28,238
  • 6
  • 56
  • 88