[Table("Child", Schema = "dbo")]
public partial class Child
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
public int? Parent1Id { get; set; }
public int? Parent2Id { get; set; }
public virtual Parent Parent1 {get; set}
public virtual Parent Parent2 {get; set}
}
[Table("Parent", Schema = "dbo")]
public partial class Parent
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
public virtual Child Child1 { get; set; }
public virtual Child Child2 { get; set; }
//modelBuilder below would work if I had this
//public virtual ICollection<Child> Child1 { get; set; }
}
This is meant to be one-to-one relationship between Parent-Child. Parent1Id and Parent2Id are nullable.
I only found examples (with FluentAPI) for one-to-many relationship and if I had a collection of Child in Parent I'd have to do something like:
modelBuilder.Entity<Parent>()
.HasMany(e => e.Child1)
.WithOptional(e => e.Parent1)
.HasForeignKey(e => e.Parent1Id);
modelBuilder.Entity<Parent>()
.HasMany(e => e.Child2)
.WithOptional(e => e.Parent2)
.HasForeignKey(e => e.Parent2Id);
Child will have 2 FK referencig Parent. Parent has no FK referencing child.
My question is, how can I do this as one-to-one relationship using EF 6.x? I saw the HasOne() method but that's from EFCore so I'm out of options in this one.
Thanks