[英]Entity Framework cannot connect and create Database
我不熟悉EF
,只是关注WebAPI
书籍的示例。
这是我得到的错误:
这是我拥有的DbContext
类:
namespace SportsStore.Models
{
public class ProductDbContext: DbContext
{
public ProductDbContext()
: base("SportsStoreDb")
{
Database.SetInitializer<ProductDbContext>(new ProductDbInitializer());
}
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderLine> OrderLines { get; set; }
}
}
还有一个像这样的 Initializer 类:
using System.Collections.Generic;
using System.Data.Entity;
namespace SportsStore.Models
{
public class ProductDbInitializer : DropCreateDatabaseAlways<ProductDbContext>
{
protected override void Seed(ProductDbContext context)
{
new List<Product> {
new Product() { Name = "Kayak", Description = "A boat for one person",
Category = "Watersports", Price = 275m },
new Product() { Name = "Lifejacket",
Description = "Protective and fashionable",
Category = "Watersports", Price = 48.95m },
new Product() { Name = "Soccer Ball",
Description = "FIFA-approved size and weight",
Category = "Soccer", Price = 19.50m },
new Product() {
Name = "Corner Flags",
Description = "Give your playing field a professional touch",
Category = "Soccer", Price = 34.95m },
new Product() { Name = "Stadium",
Description = "Flat-packed 35,000-seat stadium",
Category = "Soccer", Price = 79500m },
new Product() { Name = "Thinking Cap",
Description = "Improve your brain efficiency by 75%",
Category = "Chess", Price = 16m },
new Product() { Name = "Unsteady Chair",
Description = "Secretly give your opponent a disadvantage",
Category = "Chess", Price = 29.95m },
new Product() { Name = "Human Chess Board",
Description = "A fun game for the family",
Category = "Chess", Price = 75m },
new Product() { Name = "Bling-Bling King",
Description = "Gold-plated, diamond-studded King",
Category = "Chess", Price = 1200m },
}.ForEach(product => context.Products.Add(product));
context.SaveChanges();
new List<Order> {
new Order() { Customer = "Alice Smith", TotalCost = 68.45m,
Lines = new List<OrderLine> {
new OrderLine() { ProductId = 2, Count = 2},
new OrderLine() { ProductId = 3, Count = 1},
}},
new Order() { Customer = "Peter Jones", TotalCost = 79791m,
Lines = new List<OrderLine> {
new OrderLine() { ProductId = 5, Count = 1},
new OrderLine() { ProductId = 6, Count = 3},
new OrderLine() { ProductId = 1, Count = 3},
}}
}.ForEach(order => context.Orders.Add(order));
context.SaveChanges();
}
}
}
而且我也能够登录到我的 SQL Server 引擎的 localhost db。
那么我应该注意什么来解决这个问题?
好吧终于自己解决了。 是的,没有连接字符串。 很高兴我没有去人们发布为重复答案的那个兔子洞。
问题出在 Web.Config 中,以下版本为 13,我将其更改为 11,现在它可以工作了。
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.