How to pass the foreign key during the seed in Entity Framework

Viewed 3062

I am working on an ASP.NET MVC application with Entity Framework. My requirements are to insert the some default values into the tables using seed functionality.

I have successfully done this when there is no relation between the values. But I am not able to insert the foreign key reference using seed in Entity Framework.

This is the seed method:

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);
}

In the above code I have passed the default for Roles and Users table. Only one column is left i.e RoleId in Users table.

How can I get the primary key of Roles table as a foreign key for the Users table?

1 Answers

The easiest way is to fetch the role back from the data context and pass it in to the user:

// 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
                                        }
                           );

Obviously, if you're allowing a user to be in more than one role, or you expose the Role property as the Roles class, then you can just assign the value directly.

Related