是否可以在实体框架(代码优先)的种子方法中添加两个表的数据?

Posted

技术标签:

【中文标题】是否可以在实体框架(代码优先)的种子方法中添加两个表的数据?【英文标题】:Is it possible to add two table's data in Seed method in Entity Framework(Code-first)? 【发布时间】:2015-02-24 03:59:04 【问题描述】:

在我的 DataLayer 中,我有这个“种子”方法:

protected override void Seed(Context context)
            
            User u1 = new User()
            

                UserName = "dayan",
                Password = "dayan",
                Role = "Admin"

            ;
            User u2 = new User()
            
                UserName = "neranjan",
                Password = "neranjan",
                Role = "employee"
            ;

            context.Users.Add(u1);
            context.Users.Add(u2);
            base.Seed(context);    
        

这是我的用户表的样子:

所以现在我需要像这样在这个种子方法中添加更多的表数据:

         Examination e = new Examination()
            
                Description = "fromda console",
                CutOffMark = 1000,
                QuestionID = new List<Question>()
                 
                    new Question()
                    
                        QuestionDes = "Question",
                        Answer1 = "11",
                        Answer2 = "22",
                        Answer3 = "33",
                        Answer4 = "44",
                        Correct = 1
                    
                
            ; 

我需要这种方法的目的是因为我使用的是代码优先实体框架 我需要确保当我删除数据库并再次创建数据库时,这些行应该写入这些表中。

你能告诉我如何解决这个问题吗... 谢谢!!

【问题讨论】:

你为什么不能把它也放在你的种子方法中? 【参考方案1】:

这就是我解决它的方法......

public class ContextSeeder : DropCreateDatabaseIfModelChanges<Context>

    protected override void Seed(Context context)
    
        Examination e1 = new Examination()
        
            Description = "Science",
            CutOffMark = 10,
            QuestionID = new List<Question>()
             
                new Question()
                
                    QuestionDes = "What is a data bus?",
                    Answer1 = "It carries a word to or from memory",
                    Answer2 = "It is used to store intermediate data and instructions",
                    Answer3 = "It decodes the instructions",
                    Answer4 = "It contains the instruction that is being executed",
                    Correct = 1
                    //ExaminationID = 1
                
            
        ;
        Examination e2 = new Examination()
        
            Description = "Science",
            CutOffMark = 10,
            QuestionID = new List<Question>()
             
                new Question()
                
                    QuestionDes = "What is program counter?",
                    Answer1 = "It keeps track of the memory address of the instruction that is to be executed next.",
                    Answer2 = "It is used to store intermediate data and instructions",
                    Answer3 = "It decodes the instructions",
                    Answer4 = "It contains the instruction that is being executed",
                    Correct = 1
                    //ExaminationID = 1
                
            
        ;
        Examination e3 = new Examination()
        
            Description = "Science",
            CutOffMark = 10,
            QuestionID = new List<Question>()
             
                new Question()
                
                    QuestionDes = "Expand SD RAM.?",
                    Answer1 = "Synchronous Dynamic Random Access Memory.",
                    Answer2 = "It is used to store intermediate data and instructions",
                    Answer3 = "It decodes the instructions",
                    Answer4 = "It contains the instruction that is being executed",
                    Correct = 1
                    //ExaminationID = 1
                
            
        ;
        Examination e4 = new Examination()
        
            Description = "Computer Science",
            CutOffMark = 40,
            QuestionID = new List<Question>()
             
                new Question()
                
                    QuestionDes = "What is Instruction register?",
                    Answer1 = "Stores a copy of current instruction.",
                    Answer2 = "It is used to store intermediate data and instructions",
                    Answer3 = "It decodes the instructions",
                    Answer4 = "It contains the instruction that is being executed",
                    Correct = 1
                    //ExaminationID = 1
                
            
        ; 

        User u1 = new User()
        

            UserName = "dayan",
            Password = "dayan",
            Role = "Admin"

        ;
        User u2 = new User()
        
            UserName = "neranjan",
            Password = "neranjan",
            Role = "employee"
        ;

        context.Examinations.Add(e1);
        context.Examinations.Add(e2);
        context.Examinations.Add(e3);
        context.Examinations.Add(e4);
        context.Users.Add(u1);
        context.Users.Add(u2);
        //context.SaveChanges();
        base.Seed(context);

    

我正在使用 MVC,所以我在我的 MVC 文件夹中找到了这个名为“Global.asax”的文件,并将这个“SetInitializer”添加到其中。原来是这样的……

public class MvcApplication : System.Web.HttpApplication
    
        protected void Application_Start()
        
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
            **Database.SetInitializer(new ContextSeeder());**
        
    

然后我运行了我的主页。这。它自动将我的数据对象插入到数据库中...... 我的主页是这样的......

    @using (html.BeginForm("Results", "Exam"))

    <table>
        <tr>
            <td>
                @grid.GetHtml(columns: new[]
                        grid.Column("ID"),
                        grid.Column("QuestionDes"),
                        grid.Column("Answer1"),
                        grid.Column("Answer2"),
                        grid.Column("Answer3"),
                        grid.Column("Answer4")
                    )
            </td>
            <td>
                @Html.DropDownList("Answer1", new SelectList(ViewBag.sel, "Value", "Text"), new  @id = "1" )      
                @Html.DropDownList("Answer2", new SelectList(ViewBag.sel, "Value", "Text"), new  @id = "2" ) 
                @Html.DropDownList("Answer3", new SelectList(ViewBag.sel, "Value", "Text"), new  @id = "3" ) 
                @Html.DropDownList("Answer4", new SelectList(ViewBag.sel, "Value", "Text"), new  @id = "4" )             

            </td>
        </tr> 
    </table>      
    <input type="submit" value="Submit"/>


控制器:

public ActionResult Examination()
        
IService ser = new Service();
        //taking all the list questions passed from the LoadQuestions_ToTheGridview() method
        List<Entities.Question> list = ser.LoadQuestions_ToTheGridview();
        ViewBag.qlist = list;

        List<Models.SelectedListItems> selList = new List<Models.SelectedListItems>();
        selList.Add(new Models.SelectedListItems  Text = "----Select----", Value = "0" );
        selList.Add(new Models.SelectedListItems  Text = "Answer 1", Value = "1" );
        selList.Add(new Models.SelectedListItems  Text = "Answer 2", Value = "2" );
        selList.Add(new Models.SelectedListItems  Text = "Answer 3", Value = "3" );
        selList.Add(new Models.SelectedListItems  Text = "Answer 4", Value = "4" );

        ViewBag.sel = selList;


        return View(list);
        

谢谢!!!!

【讨论】:

以上是关于是否可以在实体框架(代码优先)的种子方法中添加两个表的数据?的主要内容,如果未能解决你的问题,请参考以下文章

实体框架代码优先 - 通过主键将子实体添加到父实体

调试代码优先的实体框架迁移代码

使用实体框架和代码优先方法创建数据库时,是不是可以从 SSMS 在数据库表上创建索引

如果我们使用实体框架和代码优先方法,是不是可以在给定路径上创建数据库(Sql Server compact)?

实体框架代码优先迁移 - 我可以针对以前的迁移

代码优先实体框架。急切加载,验证然后保存导致错误