我正在尝试使用存储库模式建立“学生有很多StudentRecords”关系。当我遇到以下错误时执行迁移。请告诉我应该在模型创建方法中做什么。
“属性'Student.StudentRecord'的类型为'StudentRecord',当前数据库提供程序不支持该属性。请更改属性CLR类型,或者使用'[NotMapped]'属性或使用'EntityTypeBuilder来忽略该属性。 “忽略”。
public class Student : BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string EnrollmentNo { get; set; }
public StudentRecord StudentRecord { get; set; }
}
这是我的映射类和Context在modelCreating mathod上。
class StudentMap
{
public StudentMap(EntityTypeBuilder<Student> entityBuilder)
{
entityBuilder.HasKey(t => t.Id);
entityBuilder.Property(t => t.FirstName).IsRequired();
entityBuilder.Property(t => t.LastName).IsRequired();
entityBuilder.Property(t => t.Email).IsRequired();
entityBuilder.Property(t => t.EnrollmentNo).IsRequired();
entityBuilder.Property(t => t.StudentRecord).IsRequired();
}
}
public class ApplicationContext : DbContext
{
public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
new StudentMap(modelBuilder.Entity<Student>());
new StudentRecordMapp(modelBuilder.Entity<StudentRecord>());
}
}
答案 0 :(得分:1)
在OnModelCreating
中:
modelBuilder.Entity<StudentRecord>()
.HasOne(x => x.Student)
.WithMany(x => x.StudentRecords)
.HasForeignKey(x => x.StudentID)
.OnDelete(DeleteBehavior.Restrict);
您的实体:
public class Student
{
public int ID { get; set; }
public virtual ICollection<StudentRecord> StudentRecords { get; set; }
}
public class StudentRecord
{
public int ID { get; set; }
public int StudentID { get; set; }
public virtual Student Student { get; set; }
}