我正在使用带有实体框架的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 = "[email protected]",
                  Password = password,
                  Gender = "Male",
                  Islocked = "false",
                  CreatedDate = DateTime.Now,
                 **Foreign key for Users table**
              }
            );

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


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

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

最佳答案

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

// 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 = "[email protected]",
                                         Password = password,
                                         Gender = "Male",
                                         Islocked = "false",
                                         CreatedDate = DateTime.Now,
                                         RoleId = userRole.Id
                                        }
                           );


显然,如果允许用户担任多个角色,或者将Role属性公开为Roles类,则可以直接分配值。

关于c# - 如何在Entity Framework的种子期间传递外键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47186784/

10-13 07:09