由于标题由于某种原因说明我的数据库在创建指定CreateDatabaseIfNotExists时没有被创建,所以在使用drop时工作正常,如果模型更改则删除。未创建数据库我在视图中收到错误,因为数据为空。
的DbContext
public class SchemaDBContext : DbContext
{
public SchemaDBContext()
{
Database.SetInitializer(new SchemaDBInitializer());
}
public DbSet<UserRole> UserRoles { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<SalesStaff> SalesStaffs { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<CreditCard> CreditCards { get; set; }
public DbSet<Enquiry> Enquiries { get; set; }
public DbSet<Trip> Trips { get; set; }
public DbSet<TripImage> TripImages { get; set; }
public DbSet<Coach> Coaches { get; set; }
public DbSet<Ticket> Tickets { get; set; }
public DbSet<Review> Reviews { get; set; }
public DbSet<CartItem> CartItems { get; set; }
public DbSet<ShoppingCart> ShoppingCarts { get; set; }
public DbSet<OrderItem> OrderItems { get; set; }
public DbSet<Order> Orders { get; set; }
}
初始化程序
public class SchemaDBInitializer : CreateDatabaseIfNotExists<SchemaDBContext>
{
protected override void Seed(SchemaDBContext context)
{
var customers = generateCustomers();
customers.ForEach(s => s.ShoppingCart = new ShoppingCart());
customers.ForEach(s => context.Customers.Add(s));
context.SaveChanges();
var salesStaffs = generateSalesStaffs();
salesStaffs.ForEach(s => context.SalesStaffs.Add(s));
context.SaveChanges();
var customerUsers = customers.Select(u => u.User).ToList();
var salesStaffUsers = salesStaffs.Select(u => u.User).ToList();
var userRoles = new List<UserRole>
{
new UserRole()
{
Role = "Customer",
Users = customerUsers
},
new UserRole()
{
Role = "SalesStaff",
Users = salesStaffUsers
}
};
userRoles.ForEach(s => context.UserRoles.Add(s));
context.SaveChanges();
var trips = generateTrips();
trips.ForEach(s => context.Trips.Add(s));
context.SaveChanges();
var tickets = generateTickets(customers, trips);
tickets.ForEach(s => context.Tickets.Add(s));
context.SaveChanges();
var reviews = generateReviews(customers, trips);
reviews.ForEach(s => context.Reviews.Add(s));
context.SaveChanges();
var enquiries = generatEnquiries(customers, salesStaffs);
enquiries.ForEach(s => context.Enquiries.Add(s));
context.SaveChanges();
var orders = generateOrders(customers);
orders.ForEach(order => context.Orders.Add(order));
context.SaveChanges();
}
}
初始化程序不会调用种子方法。