Code First 中的一对多关系播种

2024-05-02

我得到了以下简单模型,该模型正在代码优先方法中实现。部门和课程是一对多的关系。一个系可以有很多门课程,而一门课程可以只属于一个系。这是模型。

public class Department
{
    public int DepartmentId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Course> Courses { get; set; } 
       }

 public class Course
{
    public int CourseId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public int DepartmentId { get; set; } 
    public virtual Department Department { get; set; }

}

我的问题是我想给它们播种。我希望种子函数中至少有 5 个值。这是种子函数。

public class DataInitializer : DropCreateDatabaseIfModelChanges<StudentRecordContext>
{
    protected override void Seed(StudentRecordContext context)
{
    var departments = new  List<Department>
     {
        new Department {  DepartmentId = 1, Title = "English", Description ="English     Department",  Courses = new List<Course>() },
        new Department {  DepartmentId= 2,Title = "Chemistry",   Description ="chemistry department", Courses = new List<Course>() },
        new Department {  DepartmentId= 3,Title = "Mahematics", Description ="mathematics department", Courses = new List<Course>() },
        new Department {  DepartmentId= 4,Title = "Philosophy",  Description ="philosophy department", Courses = new List<Course>() },
        new Department {  DepartmentId= 5,Title = "Biology",     Description ="biology department", Courses = new List<Course>() }
    };                                                           
    departments.ForEach( t => context.Departments.Add(t));
    context.SaveChanges();


    var courses = new List<Course>
    {
        new Course { CourseId = 1055, Title = "Classic English",  Description = "Some        Description", DepartmentId = 1 },
        new Course { CourseId = 2055, Title = "Applied Chemistry",  Description = "Some Description", DepartmentId = 2 },
        new Course { CourseId = 2056, Title = "Applied Mathematics", Description = "Some Description", DepartmentId = 3 },
        new Course { CourseId = 3041, Title = "MetaPhysics",  Description = "Some Description", DepartmentId = 4 },
        new Course { CourseId = 3024, Title = "Molecular Biology", Description = "Some Description", DepartmentId = 5 },
    };
    courses.ForEach(t => context.Courses.Add(t));
    context.SaveChanges();

但这不起作用。我是 EF 和 Code First 的新手...并且截止日期即将到来...任何人都可以帮助我,因为播种数据库的正确方法是什么。


不要在中设置主键Seed()方法。实体框架将知道名称中带有 Id 的属性将是主键。

在您的系统中尝试以下操作Seed() method:

protected override void Seed(StudentRecordContext context)
{
    var departments = new  List<Department>
    {
        // this will have DepartmentId = 1
        new Department { Title = "English", Description ="English Department",  Courses = new List<Course>() },
        // more departments
    };
    departments.ForEach(d => context.Departments.Add(d));
    context.SaveChanges();

    var courses = new List<Course>
    {
        // this will have CourseId = 1
        new Course { Title = "Classic English",  Description = "Some Description", Department = departments.FirstOrDefault(d => d.DepartmentId == 1) },
        // this will have CourseId = 2
        new Course { Title = "Drama",  Description = "Some Description", Department = departments.FirstOrDefault(d => d.DepartmentId == 1) },
        // both of the above courses will be added to Department with DepartmentId = 1
        // more courses
    };
    courses.ForEach(c => context.Courses.Add(c));
    context.SaveChanges();

    // now add the two courses to the department
    departments[0].Courses.Add(courses[0]); // in list departments at index 0 add course from list courses at index 0
    departments[0].Courses.Add(courses[1]); // in list departments at index 0 add course from list courses at index 1
    context.SaveChanges();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Code First 中的一对多关系播种 的相关文章

随机推荐

  • OnIdle 事件中的异常不会冒泡

    在我的主窗体上 我订阅了两个事件 Application ThreadException 和 Application Idle 理论上 任何未捕获的异常都应该冒泡到主窗体 但是 如果异常发生在 OnIdle 事件中 则此方法不起作用 系统就
  • Altair 中具有自定义置信区间的折线图

    假设我有下面的数据框 我检查了文档 https altair viz github io gallery line with ci html但它仅基于单个列 可重现的代码 x np random normal 100 5 100 data
  • Visual Studio 中的 HTML5 Javascript API Intellisense 支持

    我开始使用 HTML5 CSS3 和新的 JavaScript API 我在 VS 2010 中注意到它不支持新的 JavaScript API 我想知道我是否可以对此做些什么 所以在 Vs2010 中如果我输入 var canvas do
  • SQL DROP TABLE 外键约束

    如果我想像这样删除数据库中的所有表 它会处理外键约束吗 如果没有 我该如何处理 GO IF OBJECT ID dbo Course U IS NOT NULL DROP TABLE dbo Course GO IF OBJECT ID d
  • core.async不是违背Clo​​jure原则吗?

    我看到许多 Clo jure 程序员对新的 core async 库充满热情 尽管它看起来很有趣 但我很难看出它如何符合 Clojure 原则 所以我有以下问题 它在任何地方都使用可变状态 正如函数名称通过感叹号所暗示的那样 例如 alt
  • 更新 Doctrine 后 Symfony 中的“ObjectManager 和 EntityManagerInterface 之间的兼容性”是什么?

    在我的 Symfony 项目中尝试更新 composer update 后出现错误 我寻找解决方案 发现有必要修改实体和构造函数中的使用和类型提示 我已经完成了 然后 我重新启动更新 但出现了不同的错误 并且更新未完全完成 结果 我的网站已
  • Heroku上传-预编译资产失败

    我需要帮助 当尝试将我的应用程序上传到heroku时 我收到此错误 有人知道为什么吗 有几个是错的 谢谢 Using rake 10 1 0 Using tlsmail 0 0 1 Using uglifier 2 1 2 Your bun
  • SVN存储库内容

    我已经设置了 VisualSvn Server 创建了一个存储库 并使用 AnkhSVN 向其中添加了 Visual Studio 解决方案 存储库的 url 类似于https msi pc svn MyProj 由于我的无能 一个问题 此
  • Objective-C / Cocoa Touch 中的 HTML 字符解码

    首先 我发现了这个 https stackoverflow com questions 659602 objective c html escape unescapeObjective C HTML 转义 unescape https st
  • 使用 Beautiful Soup - Python 查找 HTML 中 1 级内的所有文本

    我需要用美丽的汤来完成以下任务 HTML 示例 div Text1 div Text3 div div 我需要对此进行搜索 以便在列表的单独实例中返回给我 Text1 Text2 Text3 我尝试执行 findAll div 但它多次重复
  • LinkedIn OAuth 缺少必需参数“client_id”

    我正在使用 LinkedIn API 并尝试发出请求 但是当我尝试获取 accesstoken 时 我在 json 打印中收到以下错误 Array error gt missing parameter error description g
  • 使用ggmap在地图上绘制等高线

    我有洛杉矶港地区的颗粒物浓度差异 之后 之前 我正在尝试使用 ggmap 在地图上绘制浓度等值线 但结果看起来很不同 我使用的代码如下所示 数据位于代码下方 Code 安装 packages ggmap library ggmap PM r
  • 对 smtp.live.com 和 TIdSmtp(Indy、Delphi)的 SSL 支持

    我正在尝试连接到 smtp live com 发送电子邮件 live com 自 2009 年以来显然支持免费的 pop3 smtp 但这对我来说完全是新闻 当我尝试连接到 smtp live com 端口 587 时 会发生以下情况 Me
  • 如何使用 Core Data (iPhone) 存储 CLLocation?

    我试图保存一个位置 然后使用 Core Location MapKit 和 Core Data 框架在地图上检索该位置 我所做的只是创建了名为 POI 的实体 并添加了诸如纬度 双精度类型 经度 双精度类型 等属性以及其他一些属性 简而言之
  • Mongoose/Mongodb更新返回值及错误处理

    我对 Mongodb update 的返回值以及如何处理它的错误有点困惑 我使用 Node js Express js 和 Mongoose js 作为我的 Mongodb 驱动程序 当我浏览许多教程时 我看到的错误处理的唯一方法是 示例
  • 使用 Template Haskell 生成函数

    是否可以使用 Template Haskell 定义函数 例如 convertStringToValue String gt Int convertStringToValue three 3 convertStringToValue fou
  • 如何从视图中删除单元测试的“@oidc.login_required”?

    I use 烧瓶样机 questions tagged flask oidc用于用户登录和pytest questions tagged pytest供测试用 对于单元测试 我想 删除 oidc require login 我怎样才能做到这
  • 按复杂对象中的列表排序

    我有两节课 public class Customer public string FirstName get set public string LastName get set public List
  • 根指令上的 Angular 2 输入参数[重复]

    这个问题在这里已经有答案了 This https angular io docs ts latest api core Input var html示例展示了如何在子组件上使用 Input 注释 我的问题是如何在根组件上使用它 例如 如果您
  • Code First 中的一对多关系播种

    我得到了以下简单模型 该模型正在代码优先方法中实现 部门和课程是一对多的关系 一个系可以有很多门课程 而一门课程可以只属于一个系 这是模型 public class Department public int DepartmentId ge