我有这些类在我的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);
,这个错误将被抛出:
给定的关键是不存在的字典。
您有任何想法解决此问题吗?谢谢。
也许这是服务器的问题。尝试将代码粘贴到简单的控制台应用程序并进行测试。我发布了我如何做到这一点的例子。 –