[英]MVC Entity Framework - Foreign Keys from multiple tables in one field
因此,我正在为现有程序构建接口,该接口是在firebird数据库之上构建的。 我已经使用firebird的数据提供程序生成了一些模型,并且试图定义一些具有奇数结构的表之间的关系,在不破坏程序的情况下我无法更改这些关系。
这是当前的结构:
public partial class JOBLINE
{
[Key, Column(Order = 0)]
public int JobNumber {get;set;}
[Key, Column(Order = 1)]
public int LineNumber {get;set;}
public string LineType {get;set;} // can be either 'Item Code' or 'Descriptor Code'
public string LineCode {get;set;}
}
public partial class ITEMMASTER
{
[Key]
public string ItemCode {get;set;}
// The other properties
}
public partial class DESCRIPTORMASTER
{
[Key]
public string DescriptorCode {get;set;}
// The other properties
}
因此,令人讨厌的是,在jobline
表中, LineCode
字段可以包含ItemMaster
或DescriptorMaster
的外键,具体取决于CodeType
字段包含的内容。
有一种简单的方法可以指定这个吗? 使用流畅的API或数据注释。 我希望有ItemMaster
和DescriptorMaster
表的列表访问器
因此,令人讨厌的是,在作业线表中,LineCode字段可以包含ItemMaster或DescriptorMaster的外键,具体取决于CodeType字段包含的内容。
您确定您的数据库(即Firebird)允许这种事情吗?
使用关系概念的数据库不允许外键列包含来自其他表的值。 外键是为了使两个表之间的关系不多。
在您的情况下,您唯一可以做的就是创建一个唯一的约束,该约束将结合这两列: LineType
和LineCode
。
因此,您可以使用“ Index
数据注释”属性,如下所示:
public partial class JOBLINE
{
[Key, Column(Order = 0)]
public int JobNumber {get;set;}
[Key, Column(Order = 1)]
public int LineNumber {get;set;}
[Index("IX_LineTypeAndLineCode", 1, IsUnique = true)]
public string LineType {get;set;}
[Index("IX_LineTypeAndLineCode", 2, IsUnique = true)]
public string LineCode {get;set;}
}
或使用如下所示的流利配置:
modelBuilder.Entity<JOBLINE>()
.Property(p => p.LineType)
.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_LineTypeAndLineCode") { IsUnique = true, Order = 1 }));
modelBuilder.Entity<JOBLINE>()
.Property(p => p.LineCode)
.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_LineTypeAndLineCode") { IsUnique = true, Order = 2 }));
凭借独特的约束您确保每个的foreach LineType
价值JOBLINE
桌子上有一个独特的价值LineCode
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.