将层次结构映射到实体框架中的diferente表键字段

时间:2014-05-27 20:27:51

标签: c# oracle entity-framework mapping

我的朋友再一次需要你的指导。我在EF中遇到错误:“ORA-00904:”Extent1“。”PERSONID“:无效的标识符”。我有3个类:父类“Person”和子类“PersonLegal”和“PersonPhysical”简化如下:

class Person {
    int Id;
    type SomeProperty;
}

class PersonPhysical : Person {
    type OtherProperty;
}

class PersonLegal : Person {
    type AnotherProperty;
}

事实上,Oracle抱怨是正确的,因为表PERSONPHYSICAL和PERSONLEGAL不包含这样的属性PERSONID。相反,他们有PERSONPHYSICALID和PERSONLEGALID。人有人。如何告诉EF我想在映射中为这些属性设置不同的列名?

1 个答案:

答案 0 :(得分:1)

在您的DbContext类重写方法OnModelCreating中使用流畅的API定义映射并尝试以下代码:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("Person");
        });
        modelBuilder.Entity<PersonLegal>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("PersonLegal");
        });
        modelBuilder.Entity<PersonPhysical>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("PersonPhysical");
        });
        modelBuilder.Entity<Person>()
            .Property(t => t.Id)
            .HasColumnName("PERSONID");
        modelBuilder.Entity<PersonLegal>()
            .Property(t => t.Id)
            .HasColumnName("PERSONLEGAL");
        modelBuilder.Entity<PersonPhysical>()
            .Property(t => t.Id)
            .HasColumnName("PERSONPHYSICAL");

        base.OnModelCreating(modelBuilder);
    }

并向您的DbContext类添加3个propeties:

public virtual DbSet<Person> People { get; set; }
public virtual DbSet<PersonLegal> PersonLegals { get; set; }
public virtual DbSet<PersonPhysical> PersonPhysicals { get; set; }