播种数据库实体框架6 [英] Seeding database Entity Framework 6

查看:66
本文介绍了播种数据库实体框架6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Entity Framework 6并为测试数据库创建种子数据。除了一个问题,其他所有方法都可以正常工作。

I'm using Entity Framework 6 and creating seed data for a test database. All is working except for one problem.

我的某些班级在将对象添加到列表之前检查重复的ID。这是一种典型的模式:

Some of my classes check for a duplicate ID before adding an object to a list. This is a typical pattern:

   private Assignment FindAssignment(VideoCourse course) {
        Assignment assignment = assignments.Find(x => x.Course.Id == course.Id);
        if (assignment == null) {
            assignment = new Assignment(this, course);
            assignments.Add(assignment);
        }
        return assignment;
    }

这在我的种子中失败了(我不能添加多门课程)覆盖,因为所有课程的 course.Id 均为0,直到将它们保存到数据库为止。

This fails (I can't add more than one course) in my Seed override because course.Id is 0 for all courses until they've been saved to the database.

I' ve尝试在代码中的多个位置调用 SaveChanges(),但这确实使上下文混乱,并导致其他对象无法保存。

I've tried calling SaveChanges() at multiple places in the code but that really messes with the context and results in other objects not being saved.

问题是-如何将对象保存到数据库中以便可以设置其ID?

So the question - how do I get objects saved to the database so their Id's can be set?

推荐答案

事实证明,解决问题的最简单方法是在代码中为对象分配其ID,而不是等待数据库完成操作。

It turned out that the easiest way to solve the problem was to assign objects their Id in code, rather than waiting for the database to do it.

这篇关于播种数据库实体框架6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆