首页 > 解决方案 > 如何使用 EF Core(存储库模式)建立一对多关系

问题描述

我正在尝试使用存储库模式建立关系“学生有很多学生记录”。当我运行迁移时面临以下错误。请让我知道我应该在模型创建方法上做什么。

“属性‘Student.StudentRecord’的类型为‘StudentRecord’,当前数据库提供程序不支持。要么更改属性 CLR 类型,要么使用‘[NotMapped]’属性或使用‘EntityTypeBuilder.Ignore’忽略该属性'OnModelCreating'。”

  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; }
}  

这是我在模型创建方法上的映射类和上下文。

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>());
    }
}  

标签: c#asp.netentity-frameworkasp.net-coreef-code-first-mapping

解决方案


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; }
}

推荐阅读