实体框架核心一对多不使用集合,是可能的吗?



我有问题从代码创建首先在数据库中的结构,如以下:

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

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;} 
}

我尝试使用Fluent API(这是强制性的,我使用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);
});

我得到错误: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.

不,这是不可能的,没有集合将是一对一的关系

试试这个

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;} 
}

但是如果你仍然想要一对一的

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;} 
}

或者如果你只使用一个LeftSideGlass或RightSideGlass也许它可以有意义,而不是2个属性只使用一个。你可以添加一个bool标记"IsLeft"例如,

相关内容

  • 没有找到相关文章

最新更新