如何在实体框架中的种子期间传递外键

时间:2017-11-08 18:09:57

标签: c# entity-framework

我正在使用Entity Framework开发ASP.NET MVC应用程序。我的要求是使用种子功能将一些默认值插入表中。

当值之间没有关系时,我已成功完成此操作。但我无法在Entity Framework中使用种子插入外键引用。

这是种子方法:

protected override void Seed(VBlog.DbLayer.DbInitializer context)
{
    //this(AddOrUpdate) will check first is there is alrady record exists or not in the database.
    context.Roleses.AddOrUpdate(x => x.RoleName,
            // master data
            new Roles { RoleName = "Admin", Weightage = 3 },
            new Roles { RoleName = "User", Weightage = 1 }
           );

    //adding the mast data for user table
    context.Userses.AddOrUpdate(x=>x.EmailId,
             new Users()
              {
                  FirstName = "vir",
                  LastName = "acker",
                  EmailId = "vir.acker@xyz.com",
                  Password = password,
                  Gender = "Male",
                  Islocked = "false",
                  CreatedDate = DateTime.Now,
                 **Foreign key for Users table**
              }
            ); 

    //context.Userses.AddRange(defaultUserDataList);
    base.Seed(context);
}

在上面的代码中,我已经传递了Roles and Users表的默认值。只留下一列,即RoleId表中的Users

如何将Roles表的主键作为Users表的外键?

1 个答案:

答案 0 :(得分:3)

最简单的方法是从数据上下文中取回角色并将其传递给用户:

// Create/Update the roles
context.Roleses.AddOrUpdate(x => x.RoleName,
                            new Roles { RoleName = "Admin", Weightage = 3 },
                            new Roles { RoleName = "User", Weightage = 1 }
                           );

// Ensure the roles are in the database
context.SaveChanges();

// Fetch the "user" role
Roles userRole = context.Roleses.Single(r => r.RoleName == "User");

// Create/Update the user
context.Userses.AddOrUpdate(x=>x.EmailId,
                            new Users() {
                                         FirstName = "vir",
                                         LastName = "acker",
                                         EmailId = "vir.acker@xyz.com",
                                         Password = password,
                                         Gender = "Male",
                                         Islocked = "false",
                                         CreatedDate = DateTime.Now,
                                         RoleId = userRole.Id
                                        }
                           );

显然,如果您允许用户处于多个角色中,或者将Role属性公开为Roles类,则可以直接指定该值。