获取实体框架以生成我的表

时间:2011-07-14 14:46:28

标签: entity-framework-4 ef-code-first

我正在尝试让Entity Framework Code First为我创建一个数据库,但似乎遇到了它实际上没有创建表的问题。

在我的Web.Config中我有连接字符串设置并指向数据库(没有表格)我设置:

    <connectionStrings>
    <add name="DataContext" connectionString="Server=.\SQLEXPRESS;Database=MyDatabase;Trusted_Connection=Yes;" providerName="System.Data.SqlClient" />
</connectionStrings>

在我的Domain项目中的DataConext.cs类中,我有以下内容:(我正在使用Altairis.Web.Security插件来帮助提供会员资格)

public class DataContext : DbContext
{
    public DbSet<Faq> Faqs { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Maps to the expected many-to-many join table name for roles to users.
        modelBuilder.Entity<User>()
       .HasMany(u => u.Roles)
       .WithMany(r => r.Users)
       .Map(m =>
       {
           m.ToTable("RoleMemberships");
           m.MapLeftKey("UserName");
           m.MapRightKey("RoleName");
       });
    }
}

public class DataContextInitializer : CreateDatabaseIfNotExists<DataContext>
{
    protected override void Seed(DataContext context)
    {
        // create roles
        var roles = new List<Role>{
            new Role{RoleName = "Administrator"},   // admin area: admin user
            new Role{RoleName = "User"},            // admin area: normal user               
            new Role{RoleName = "Client"}           // front end: normal user
        };

        roles.ForEach(r => context.Roles.Add(r));
    }
}

在我的Web项目Global.asax.cs中,我有:

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        Database.SetInitializer(new DataContextInitializer());
    }

所有内容都会编译并消失,但数据库表永远不会为我生成。从网上阅读我认为这可能是由于数据库.SetInitializer,但我不确定它应该调整到什么位置?

任何指导我正确方向的帮助都会很棒!我在家用电脑上工作但是在另一台PC上运行这个项目因为某种原因而无法正常工作 - 通常;)

谢谢, 富

2 个答案:

答案 0 :(得分:0)

我认为您在设置初始化程序时需要使用“DataContext”类型:

Database.SetInitializer<DataContext>(new DataContextInitializer())

当您对表数据进行种子处理时,您需要保存更改:

protected override void Seed(DataContext context)
{
    // create roles
    var roles = new List<Role>{
        new Role{RoleName = "Administrator"},   // admin area: admin user
        new Role{RoleName = "User"},            // admin area: normal user               
        new Role{RoleName = "Client"}           // front end: normal user
    };

    roles.ForEach(r => context.Roles.Add(r));
    context.SaveChanges();  // save changes to db
}

答案 1 :(得分:0)

好的,终于让这个工作了。感谢Ladislav Mrnka的链接,我将global.asax改为:

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);


        var initr = new DataContextInitializer();
        Database.SetInitializer<DataContext>(new DataContextInitializer());
        using (var db = new DataContext())
        {
            db.Database.CreateIfNotExists();
        }

        using (var db1 = new DataContext())
        {
            initr.Seed(db1);
        }
    }

我还使用BumbleB2na的建议调整了我的DataContextInitializer。完成的课程如下所示:

public class DataContextInitializer : CreateDatabaseIfNotExists<DataContext>
{
    public void Seed(DataContext context)
    {
        // create roles
        var roles = new List<Role>{
            new Role{RoleName = "Administrator"},   // admin area: admin user
            new Role{RoleName = "User"},            // admin area: normal user               
            new Role{RoleName = "Client"}           // front end: normal user
        };

        roles.ForEach(r => context.Roles.Add(r));
        context.SaveChanges();
    }
}

如果我让Entity Framework为我创建数据库而不是在运行代码之前自己创建数据库,它现在可以正常工作。希望这有助于其他人!