2017-08-30 49 views
1

我有表模型在我的客户数据库:实体框架:在类似的数据库映射多个类似的类一个表

public class Doctor 
{ 
    public int Id { get; set; } 
    public int Filial { get; set; } 
    public string ShortName { get; set; } 
    public string FullName { get; set; } 
    public string Phone { get; set; } 

    public int? DepartmentId { get; set; } 
    public Department Department { get; set; } 
} 

public class DoctorConfiguration : EntityTypeConfiguration<Doctor> 
{ 
    public DoctorConfiguration() 
    { 
     ToTable("DOCTOR"); 
     Property(d => d.Id).HasColumnName("DCODE").IsRequired(); 
     Property(d => d.Filial).HasColumnName("FILIAL"); 
     Property(d => d.ShortName).HasColumnName("DNAME"); 
     Property(d => d.FullName).HasColumnName("FULLNAME"); 
     Property(d => d.Phone).HasColumnName("DPHONE"); 

     Property(d => d.DepartmentId).HasColumnName("DEPNUM");    

     HasKey(d => d.Id);    
     HasOptional(d => d.Department).WithMany(dep => dep.Doctors).HasForeignKey(d => d.DepartmentId);    
    } 

} 

最近其他客户端来了。他们的数据库大多数是相同的模型,但是一些字段已经将类型从int更改为long。 新的医生模型的样子:

public class Doctor 
{ 
    public long Id { get; set; } 
    public long Filial { get; set; } 
    public string ShortName { get; set; } 
    public string FullName { get; set; } 
    public string Phone { get; set; } 

    public long? DepartmentId { get; set; } 
    public Department Department { get; set; } 
} 

如何将新的医生模型格式正确映射到同一个表“医生”?

该应用程序使用Firebird数据库。 “旧”客户端版本不支持长数字格式。

如果创建了类似的Doctor配置,则会出现一个错误: “实体类型'DoctorInt'和'Doctor'不能共享表'DOCTOR',因为它们不在同一类型层次结构中或者没有有效的到一个具有匹配的主键的外键关系。“

我知道关于逐层次表(TPH)的继承。看起来在这种情况下它不起作用。

Doctor的类型只是这个问题的许多类似类型之一。应用程序中的代码与第一个模型格式相关联。我不想改变这一切... 我想重用现有的功能。

+0

假设ID字段是主键我不认为你可以。 –

+0

可以肯定......你有'int'和'long',但你只能期望int兼容值,对吧?另外,我还没有真正理解你的场景......都是应该在相同的应用程序中存在的医生类,在相同的DbContext中,针对不同的(但相似的)数据库或完全相同的数据库实例? ... – grek40

+0

@ grek40我想,在这种情况下,我必须具有“int”和“long”兼容值。旧客户端拥有Firebird数据库的版本,其中“long”不受支持。新客户端拥有'long'数据库版本。我可以在代码中将int转换为long。代码中的操作将会“长”。 “ – Andriy

回答

0

如果我不要误会,你需要支持新老和数据库使用相同的代码和数据库的不同仅仅在ID的大小

一种方法是使用泛型和条件编译

public class Doctor<T> { 
    public T Id { get; set; } 
    public int Filial { get; set; } //Suposing Filial is not a foreing key 
    public string ShortName { get; set; } 
    public string FullName { get; set; } 
    public string Phone { get; set; } 

    public T? DepartmentId { get; set; } 
    public Department Department { get; set; } 

} 

当istantiating:

#ifdef USELONG 
var d = new Doctor<long>(); 
#else 
var d = new Doctor<int>(); 
#endif 

或用一个工厂模式(其中CreateDoctor可以是医生类的一个静态方法):

var d = Doctor.CreateDoctor(); 
+0

感谢您的回答,但实施此方法后,错误上升:“类型' Schedule.DB.Models.Doctor'1 [System.Int32]'未映射。请检查该类型是否未使用Ignore方法或NotMappedAttribute数据注释明确排除。验证类型被定义为一个类,不是原始的或通用的,并且不从EntityObject继承。“看起来像泛型类不支持作为实体框架中的模型:https://stackoverflow.com/questions/21513534/ -generic类 - 不支持-AS-模型,在实体框架 – Andriy

相关问题