c# - 从代码中使用 EntityFramework 重构数据库

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

我正在调整 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; }
}

我还创建了额外的模型 Foo , FooMakerCategory .其他模型已存在于 MVCMusicStore 示例中。

我创建了一个 SampleFooData继承自 DropCreateDatabaseIfModelChanges<FooStoreEntities> 的类并覆盖 seed为新表播种的方法。

我更改了 Application_Start Global.asax.cs 中的方法包含 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 应用程序的所有旧表。

当我执行网络应用程序时,它命中了 SetInitializer断点但是它似乎没有创建 SampleFooData对象并在数据库中创建新表。我错过了什么?或者有什么我不明白的基本知识吗?

最佳答案

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

你可以把

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

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

关于c# - 从代码中使用 EntityFramework 重构数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6371042/

相关文章:

c# - .NET Core 2.1 - Entity Framework : Check for duplicates before adding to DB

c# - SQL Select 数据变化时

asp.net-mvc-3 - 如何通过 App_Code 助手使用 ASP.NET MVC View 预编译?

c# - List<> 与 IEnumerable<>,在定义新类或新 View 模型类时

C# 的性能变化很快,循环次数仅增加了 0.001%

c# - 在 Android 中重新选择选项卡时如何更改 TabbedPage 图标?

c# - 将 c++ dLL 的 char 指针数组传递给 c# 字符串

.net - MVC 验证期间的简单注入(inject)器 “The operation cannot be completed because the DbContext has been disposed”

c# - 上下文在 Code First 模式下使用,代码是从 EDMX 文件生成的

asp.net - 如何将 MVC3 Hello World 应用程序部署到本地主机并配置 IIS