简体   繁体   English

为什么不创建数据库?

[英]Why is the database not created?

I use Entity Framework code-first. 我先使用实体​​框架代码。

DataBaseName - I want to create a database in SQL Server. DataBaseName-我想在SQL Server中创建一个数据库。

In web.config : 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" />

in global.asax : global.asax

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

     Database.SetInitializer(new DataContextInitializer());
 }

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

But the database is not created. 但是没有创建数据库。 What did I forget to write? 我忘了写什么?

Database.SetInitializer sets the initializer but doesn't run the initialization. Database.SetInitializer 设置初始化程序,但不运行初始化。 After Database.SetInitializer you need to add: Database.SetInitializer之后,您需要添加:

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

I don't see you adding the new data in your seed method, I guess you need to add them to datacontext so that entityframework will go create db and save the data, try something like below 我看不到您在种子方法中添加新数据,我想您需要将它们添加到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"));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM