Reputation: 1225
I am using Entity Framework to create my database. I have a table called "Departments" that seed first and then add two users. I need to use the Id from the department table to seed the user table.
context.Department.AddOrUpdate(x => x.Id,
new Department() { Id = Guid.NewGuid(), Name = "System", ImageNameLight = "", ImageNameDark = "" },
new Department() { Id = Guid.NewGuid(), Name = "Estimating", ImageNameLight = "", ImageNameDark = "" },
new Department() { Id = Guid.NewGuid(), Name = "Assembly", ImageNameLight = "dep-assy-off", ImageNameDark = "dep-assy-on" },
new Department() { Id = Guid.NewGuid(), Name = "Project Engineering", ImageNameLight = "dep-pe-off", ImageNameDark = "dep-pe-on" },
);
var firstOrDefault = context.Department.FirstOrDefault(d => d.Name == "System");
if (firstOrDefault != null)
{
var user = new ApplicationUser
{
UserName = "sysadmin",
Email = "[email protected]",
EmailConfirmed = true,
FirstName = "System",
LastName = "Admin",
RoleId = adminRole.Id,
DateCreated = DateTime.Now,
DepartmentId = firstOrDefault.Id
};
This is what I have so far but it does not work because the user is never created.
Upvotes: 0
Views: 74
Reputation: 1137
You have to save to your context first or else the seed will never work try this :
context.Department.AddOrUpdate(x => x.Id,
new Department() { Id = Guid.NewGuid(), Name = "System", ImageNameLight = "", ImageNameDark = "" },
new Department() { Id = Guid.NewGuid(), Name = "Estimating", ImageNameLight = "", ImageNameDark = "" },
new Department() { Id = Guid.NewGuid(), Name = "Assembly", ImageNameLight = "dep-assy-off", ImageNameDark = "dep-assy-on" },
new Department() { Id = Guid.NewGuid(), Name = "Project Engineering", ImageNameLight = "dep-pe-off", ImageNameDark = "dep-pe-on" },
);
context.SaveChanges();
//Do whatever with your new context
Upvotes: 2