我有這些類在我的ASP.NET MVC應用程序:問題與EF 4.1 TPH繼承映射與代碼首先
public abstract class Person {
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Student : Person {
public DateTime RegisteredOnUtc { get; set; }
public int Age { get; set; }
}
public class Teacher : Person {
public string LessonName { get; set; }
}
public class PersonMap : EntityTypeConfiguration<Person> {
public PersonMap()
: base() {
this.HasKey(t => t.PersonId);
this.Property(t => t.FirstName)
.IsRequired()
.HasMaxLength(50);
this.Property(t => t.LastName)
.IsRequired()
.HasMaxLength(50);
this.ToTable("Persons");
this.Property(t => t.PersonId).HasColumnName("PersonId");
this.Property(t => t.FirstName).HasColumnName("FirstName");
this.Property(t => t.LastName).HasColumnName("LastName");
this.Map<Student>(x => x.Requires("IsStudent").HasValue(true));
this.Map<Teacher>(x => x.Requires("IsStudent").HasValue(false));
}
}
public class StudentMap : EntityTypeConfiguration<Student> {
public StudentMap()
: base() {
this.HasKey(t => t.PersonId); // Is this need or not???
this.ToTable("Persons"); // Is this need or not???
this.Property(t => t.RegisteredOnUtc).HasColumnName("RegisteredOn");
}
}
public class TeacherMap : EntityTypeConfiguration<Teacher> {
public TeacherMap()
: base() {
this.HasKey(t => t.PersonId); // Is this need or not???
this.ToTable("Persons"); // Is this need or not???
this.Property(t => t.LessonName)
.IsRequired()
.HasMaxLength(50);
this.Property(t => t.LessonName).HasColumnName("Lesson");
}
}
public class PersonContext : DbContext {
public ObjectContext ObjectContext {
get {
return ((IObjectContextAdapter)this).ObjectContext;
}
}
public DbSet<Person> Persons { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<Teacher> Teachers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Configurations.Add(new PersonMap());
modelBuilder.Configurations.Add(new StudentMap());
modelBuilder.Configurations.Add(new TeacherMap());
}
public void Detach(object entity) {
var objectContext = ((IObjectContextAdapter)this).ObjectContext;
objectContext.Detach(entity);
}
}
但是,當我運行應用程序,出現此錯誤:
屬性'PersonId'
不是'Student'
類型的聲明屬性。通過使用Ignore
方法或NotMappedAttribute
數據註釋驗證該屬性是否未明確從模型中排除。確保它是一個有效的基本屬性。
如果從Student
和Teacher
刪除this.HasKey(t => t.PersonId);
,這個錯誤將被拋出:
給定的關鍵是不存在的字典。
您有任何想法解決此問題嗎?謝謝。
也許這是服務器的問題。嘗試將代碼粘貼到簡單的控制檯應用程序並進行測試。我發佈了我如何做到這一點的例子。 –