c# - 如何使用 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>());
}
}
解决方案
在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; }
}
推荐阅读
- python - 计算两个事件之间的时间差,同时忽略 Python 中不匹配的事件
- python - 使用 for/while 循环和 range() 列出值
- python - 在 python 中不允许 AssertionError for wordcloud 并且不要运行
- python - Scipy UnivariateSpline 在某些情况下退出代码 -1073741819
- angularjs - 如何按表达式选择自定义过滤器?
- jquery - 仅通过 indexOf 值删除 cookie.. 不是其他值
- vue.js - 如何更新 vue cli 版本?
- java - 资源 'attr/borderColor' 与配置 '' 的重复值错误。使用 me.dm7.barcodescanner:zxing:1.9.13 时?
- file-transfer - 如何将文件从 OPC UA 客户端传输到 OPC UA 服务器
- scala - 如何在scala中的List [List [Double]]中除,乘或添加任何值