【问题标题】:Refactoring Database with EntityFramework from code从代码中使用 EntityFramework 重构数据库
【发布时间】:2011-06-16 11:26:54
【问题描述】:

我正在调整 MVCMusicStore 购物车。我希望使用 EntityFramework 重构数据库 - 而不是通过服务器资源管理器。

在我的模型文件夹中,我创建了一个新的FooEntities 模型。

public class FooStoreEntities : DbContext
{
    public DbSet<Foo> Foos { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<FooMaker> FooMakers { get; set; }
    public DbSet<Cart> Carts { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<OrderDetail> OrderDetails { get; set; }
}

我还创建了额外的模型FooFooMakerCategory。 MVCMusicStore 示例中已经存在其他模型。

我创建了一个 SampleFooData 类,它继承自 DropCreateDatabaseIfModelChanges&lt;FooStoreEntities&gt; 并覆盖 seed 方法来为新表做种。

我将Global.asax.cs 中的Application_Start 方法更改为包含System.Data.Entity.Database.SetInitializer(new FooStore.Models.SampleFooData());

web.config 文件中我有:

<connectionStrings>
    <add name="FooStoreEntities"
    connectionString="Data Source=|DataDirectory|FooStore.sdf"
    providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>

FooStore.sdf 仍然包含来自 MVCMusicStore 应用程序的所有旧表。

当我执行 Web 应用程序时,它会遇到 SetInitializer 断点,但它似乎没有创建 SampleFooData 对象并在数据库中创建新表。我错过了什么?还是有什么基本的我不明白?

【问题讨论】:

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


【解决方案1】:

它只会在您使用数据库上下文时创建:请参阅Entity Framework Database.SetInitializer simply not working

你可以放

var ctx = new FooStoreEntities();
ctx.Database.Initialize(true);

在 Application_Start 中设置初始化程序之后。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多