gpt4 book ai didi

c# - 使用代码优先的 EF 4.1 中的 TPH 继承映射问题

转载 作者:行者123 更新时间:2023-11-30 16:27:53 25 4
gpt4 key购买 nike

我的 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 数据注释验证该属性是否未从模型中明确排除。确保它是有效的原始属性。

如果从 StudentTeacher 中删除 this.HasKey(t => t.PersonId); >,会抛出这个错误:

字典中不存在给定的键。

请问您有解决这个问题的想法吗?谢谢。

最佳答案

您是否尝试从 StudentMap 和 TeacherMap 中删除这两行?

this.HasKey(t => t.PersonId); // Is this need or not???

this.ToTable("Persons"); // Is this need or not???

我复制了你的代码并在没有这些行的情况下运行它,它工作得很好。

关于c# - 使用代码优先的 EF 4.1 中的 TPH 继承映射问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7462875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com