2017-08-29 22 views
0

所以我正在构建一个现有程序的接口,它是建立在firebird数据库之上的。我已经使用firebird的数据提供程序生成了一些模型,并且我正在试图定义几个具有奇怪结构的表之间的关系,如果不打破该程序,我就不会改变它。MVC实体框架 - 在一个字段中的多个表的外键

这是当前结构归结:

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场可以包含两种ItemMasterDescriptorMaster外键,这取决于什么CodeType场包含的内容。

有没有简单的方法来指定它?使用流利的API或数据注释。我希望能有对ItemMasterDescriptorMaster表列出了存取

回答

1

所以讨厌的事情是,在jobline表,该行代码字段 可以包含外键的任何ItemMaster,或 DescriptorMaster,取决于CodeType字段包含的内容。

你确定你的数据库(这是火鸟)允许这样的事情吗?

使用关系概念的数据库不允许外键列包含来自不同表的值。一个外键在这里使两个表之间的关系不再更多。

在你的情况下,你唯一能做的就是创建一个独特的约束,将这两列合并:LineTypeLineCode

所以,你可以使用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在JOBLINE表中的每个LineTypeLineCode有一个唯一的值。

+0

谢谢。我将如何处理指定关系? –

+0

没有必要添加关联关系将独特约束看作是插入到组合列中的数据的后卫。正如我在答案中所说的那样,您不能在三个表之间创建关系,就像您需要处理共享列一样。不可能。 – CodeNotFound

+0

当。啊,谢谢你的帮助 –

相关问题