我正在尝试定义这些表。
_tbl1_
id (PK)
_tbl2_
id (PK)
tbl1_id (FK)
_tbl3_
id (PK)
tbl1_id (FK)
...我可以从 Tbl1 导航到 Tbl2 或 Tbl3
或从 Tbl2 或 Tbl3 返回到 Tbl1。
虽然需要从 Tbl2 或 Tbl3 到 Tbl1 的关联,但 Tbl2 或 中的记录>Tbl3 可能不存在;所以 Tbl1 记录应该能够与我们的 Tbl2 和 Tbl3 两者或其中之一存在。
这种设计是为了从 Tbl1 的角度与两个完全不同的实体建立可选关系。
class Tbl1
{
[Key]
public int Id { get; set; }
public Tbl2 Tbl2 { get; set; }
public Tbl2 Tbl3 { get; set; }
}
class Tbl2
{
[Key]
public int Id { get; set; }
[ForeignKey("Tbl1")]
public int Tbl1Id { get; set; }
public Tbl1 Tbl1 { get; set; }
}
class Tbl3
{
[Key]
public int Id { get; set; }
[ForeignKey("Tbl1")]
public int Tbl1Id { get; set; }
public Tbl1 Tbl1 { get; set; }
}
流利...
modelBuilder.Entity<Tbl2>()
.HasRequired(e => e.Tbl1)
.WithOptional(e => e.Tbl2);
modelBuilder.Entity<Tbl3>()
.HasRequired(e => e.Tbl1)
.WithOptional(e => e.Tbl3);
使用上面我得到一个错误:
Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
这似乎暗示外键也必须是记录键。
那么,我可以这样做吗?可以吗?
我很乐意使用属性或 Fluent API 或两者来实现。
请您参考如下方法:
我认为您的 ForeignKey 属性需要引用一列并放置在导航属性之上。例如:
[ForeignKey("Tbl1Id")]
public virtual Tbl1 tbl1 {get; set;}
即使您在 Tbl1 到 Tbl2 和 Tbl3 上定义了一个导航属性,外键注释也应该在依赖类(tbl2 和 tbl3)而不是主类中定义。
我不确定这是否能解决整个问题,但也许会有所帮助。
祝你好运
