.net - 使用“模型优先”方法时如何播种数据?

标签 .net asp.net-mvc-3 entity-framework-4 seed ef-model-first

所以我正在学习MVC3和EF4。
我尝试了代码优先方法,但是这对我来说太困惑了。我可以毫无问题地创建类,但是在处理外键和彼此之间的关系时会遇到困难。

但是我首先选择模型。这样,我可以直观地设计它并查看关系在哪里。

创建模型后,它将为我创建一个SQL,然后对SQL Express数据库执行该SQL。做完了。

现在,我想要表中的数据。当然,我可以使用服务器资源管理器将其添加,但是很可能我会随着模型的变化对模型进行更改。并不断更新数据库。因此,我无法继续手动输入数据。我知道如果您首先使用代码,则可以派生DropCreateDatabaseIfModelChanges并覆盖seed方法。

但是,如何使用模型优先方法做到这一点?
我有以下代码:

 public class DatabaseInitializer : IDatabaseInitializer<BettingContext> {
    public void InitializeDatabase(BettingContext context) {
        var teams = new List<Team> {
            new Team { Name="Toronto Maple Leafs", League="NHL"},
            new Team { Name="Boston Bruins", League="NHL"},
            new Team { Name="Vancouver Canucks", League="NHL"},
            new Team { Name="Nashville Predators", League="NHL"},
            new Team { Name="Montreal Canadiens", League="NHL"},
        };
    }
}

当然,在我的全局文件中:
protected void Application_Start()
{
    Database.SetInitializer<BettingContext>(new DatabaseInitializer());
    AreaRegistration.RegisterAllAreas();

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

那么现在怎么办?我如何告诉它运行方法?我究竟做错了什么?

最佳答案

您可以有以下内容:

public class MySeedData : DropCreateDatabaseIfModelChanges<YourDataBaseContextClass>
{
    protected override void Seed(YourDataBaseContextClass context)
    {  
       // Create objects here and add them to your context DBSets...

    }
}

public class YourDataBaseContextClass : DbContext
{


}

然后,在Application_Start()中调用:
Database.SetInitializer(new MySeedData());

在您的情况下,您可以尝试手动创建DbSet(使用模型的第一类),并尝试使用上面的代码将其插入。这是Model First + Code First的混合。
public class FourthCoffeeWebContext : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
}

添加到此:CreateDatabaseIfNotExists<(Of <(<'TContext>)>)>

关于.net - 使用“模型优先”方法时如何播种数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6006152/

相关文章:

c# - MVC3 重定向到 "Unauthorized"页面不起作用?

entity-framework-4 - Entity Framework 和事务

c# - 在 C# 中模拟 CTE 递归

c# - 选择整个实体时, Entity Framework 返回过时的数据,但仅选择一个字段时, Entity Framework 返回最新数据

c# - 将匿名类型的对象作为参数传递给方法

.net - 为什么 .NET 正则表达式和 Visual Studio 的正则表达式之间存在差异?

c# - 当 Gacutil.exe 拒绝服务时如何从 GAC 中删除 dll

asp.net-mvc-3 - ASP.NET 4.3 脚手架 : Add Controller vs Add View - different behavior?

asp.net-mvc - 将 ViewData\ModelState 导出到子操作

c# - Youtube v3 API 字幕下载