Entity framework Core One to Many without use of collections, is it possible?

Viewed 283

I'm having problems creating from code-first a structure in the database like the following:

dbo.Glasses
____________
|Id(PK) | LeftSideId(FK)-Nullable | RightSideId(FK)-Nullable|

dbo.Sides
____________
|Id(PK) | Value|

Classes

public class Glass
{
    public int Id {get;set;}
    public int? LeftSideId {get;set;}
    public Side LeftSide {get;set;}
    public int? RightSideId {get;set;}
    public Side RightSide {get;set;}
}

public class Side
{ 
    public int Id {get;set;}
    public string  Value {get;set;}
    public int Glass {get;set;}
    public Glass Glass {get;set;} 

}

What I tried with Fluent API (It's mandatory I use FluentApi):

modelBuilder.Entity<Side>(entity =>
{
    entity.HasOne(side => side.Glass)
        .WithOne(glass => glass.LeftSide)
        .HasForeignKey<Glass>(glass => glass.LeftSideId)
        .OnDelete(DeleteBehaviour.ClientSetNull);

    entity.HasOne(side => side.Glass)
        .WithOne(glass => glass.RightSide)
        .HasForeignKey<Glass>(glass => glass.RightSideId)
        .OnDelete(DeleteBehaviour.ClientSetNull);
});


With this I get the error: Cannot create a relationship between 'Side.Glass' and 'Glass.RightSide ', because there already is a relationship between 'Side.Glass' and 'Glass.LeftSide '. Navigation properties can only participate in a single relationship.

1 Answers

No, it is impossible, without a collection it will be an one-to-one relation

Try this

public class Side
{ 
    public int Id {get;set;}
    public string  Value {get;set;}
  
    public virtual ICollection<Glass> LeftSideGlasses {get;set;} 
    public virtual ICollection<Glass> RightSideGlasses {get;set;} 
}

but if you still want one-to-one

public class Side
{ 
    public int Id {get;set;}
    public string  Value {get;set;}
  
    public virtual Glass LeftSideGlass {get;set;} 
    public virtual Glass RightSideGlass {get;set;} 
}

or if you use only one LeftSideGlass or RightSideGlass maybe it can make sense instead of 2 properties use the one only. You can just add a bool flag "IsLeft" for example.

Related