我的ASP.NET MVC应用程序中包含以下类:
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数据批注,验证该属性未明确从模型中排除.确保它是有效的原始属性.
如果删除此代码,则为HasKey(t => t.PersonId);从学生和老师那里,将抛出此错误:
给定的键在词典中不存在.
您有什么想法要解决吗?谢谢.
解决方法:
您是否尝试从StudentMap和TeacherMap中删除这两行?
this.HasKey(t => t.PersonId); // Is this need or not???
this.ToTable("Persons"); // Is this need or not???
我复制了您的代码,并在没有这些行的情况下运行了它,效果很好.