实体框架工作代码首先不起作用

时间:2018-03-12 06:05:55

标签: c# entity-framework ef-code-first

我无法从代码中成功创建数据库,下面是我的代码。

public class ProductDatabaseInitializer : DropCreateDatabaseIfModelChanges<ProductContext>
{
    protected override void Seed(ProductContext context)
    {
        GetCategories().ForEach(c => context.Categories.Add(c));
        GetProducts().ForEach(p => context.Products.Add(p));
    }

    private static List<Category> GetCategories()
    {
        var categories = new List<Category> {
            new Category
            {
                CategoryID = 1,
                CategoryName = "Cars"
            }
        };

        return categories;
    }

    private static List<Product> GetProducts()
    {
        var products = new List<Product> {
            new Product
            {
                ProductID = 1,
                ProductName = "Convertible Car",
                Description = "This convertible car is fast!", 
                ImagePath = "carconvert.png",
                UnitPrice = 22.50,
                CategoryID = 1
            }
        };

        return products;
    }
}

产品上下文类

public class ProductContext : DbContext
{
    public ProductContext()
        : base("WingtipToys")
    {
    }

    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<CartItem> ShoppingCartItems { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<OrderDetail> OrderDetails { get; set; }
}

Start事件的Global.asax

// Initialize the product database.
Database.SetInitializer(new ProductDatabaseInitializer());

当我运行应用程序时,不会创建数据库。

的Web.Config

<add name="WingtipToys" connectionString="Data Source=(LocalDB)\MSSQLLOCALDB;AttachDbFilename=|DataDirectory|\wingtiptoys.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />

3 个答案:

答案 0 :(得分:0)

你的种子中缺少context.SaveChanges();

答案 1 :(得分:0)

我在Global.asax

找到了上述问题的解决方案
public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            // Initialize the product database.
            Database.SetInitializer(new ProductDatabaseInitializer());

            using (var context = new ProductContext())
            {
                context.Database.Initialize(force: true);
            }
        }
    }

答案 2 :(得分:0)

我没有看到任何代码,所以我会问,但你是否采取任何行动:

protected override void OnModelCreating(ModelBuilder modelBuilder) {}

另外,您如何尝试生成数据库,是否使用“迁移”?

不要忘记您需要使用context.SaveChanges();

将更改应用于您的上下文