为什么没有创建数据库?

时间:2012-06-30 11:08:04

标签: c# asp.net-mvc-3 entity-framework ef-code-first

我首先使用Entity Framework代码。

DataBaseName - 我想在SQL Server中创建一个数据库。

web.config

<configuration>
  <connectionStrings>
    <add name="DataContext" 
         providerName="System.Data.SqlClient" 
         connectionString="Data Source=USER\SQLEXPRESS;Initial Catalog=DataBaseName;Integrated Security=True;Pooling=False;User Instance = False" />
global.asax中的

 protected override void OnApplicationStarted()
 {
     base.OnApplicationStarted();

     Database.SetInitializer(new DataContextInitializer());
 }

DataContextInitializer

namespace CodeFirstMembershipSharp
{
    public class DataContextInitializer : DropCreateDatabaseAlways<DataContext>
    {
        protected override void Seed(DataContext context)
        {
            MembershipCreateStatus Status;
            Membership.CreateUser("Demo", "123456", null, null, null, true, out Status);
            Roles.CreateRole("Admin");
            Roles.AddUserToRole("Demo", "Admin");
        }
    }
}

DataContext

public class DataContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Bid>()
            .HasRequired(a => a.Auction)
            .WithMany()
            .HasForeignKey(x => x.AuctionId).WillCascadeOnDelete(false);

        modelBuilder.Entity<Bid>()
           .HasRequired(a => a.User)
           .WithMany()
           .HasForeignKey(x => x.UserId).WillCascadeOnDelete(false);
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<Auction> Auctions { get; set; }
    public DbSet<Page> Pages { get; set; }
    public DbSet<Bid> Bids { get; set; }
}

但是没有创建数据库。我忘了写什么?

2 个答案:

答案 0 :(得分:1)

Database.SetInitializer 设置初始值设定项但不运行初始化。在Database.SetInitializer之后,您需要添加:

using (var context = new DataContext())
{
    context.Database.Initialize(false);
}

答案 1 :(得分:0)

我没有看到你在种子方法中添加新数据,我想你需要将它们添加到datacontext中,以便entityframework将创建db并保存数据,尝试类似下面的内容

namespace CodeFirstMembershipSharp
{
    public class DataContextInitializer : DropCreateDatabaseAlways<DataContext>
    {
        protected override void Seed(DataContext context)
        {
            context.Users.Add(new User{name = "Demo", password = "123456"});
            context.Roles.Add(New Role("Admin"));
        }
    }
}