【发布时间】:2013-09-04 15:55:13
【问题描述】:
我正在运行带有数据库和 SQL 身份验证的 SQL Server Express 2008 R2。我已将数据库连接添加到我的服务器资源管理器并将连接字符串添加到web.config 文件。当我调试应用程序时,它似乎正在创建一个默认数据库,例如tutorial.MVC 等,而不是拿起我在创建应用程序之前创建的数据库。
我也得到了编译错误:{"Invalid object name 'dbo.Products'."},这应该发生,因为 SQL 是:
{SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[ProductName] AS [ProductName],
[Extent1].[ProductPrice] AS [ProductPrice]
FROM [dbo].[Products] AS [Extent1]}
不存在名为 products 的表。这一定是由实体框架数据库生成的。我已将其删除,因为 Products 模型类最初是 Products,其中数据库表称为 Product(人为错误),因此无法更新 SQL。本质上我只是希望控制器映射到正确的数据库。我怀疑它没有从 connectionString 中获取数据库。尽管在调试时 StoreContext 正在拾取连接字符串。 似乎没有拿起数据库。但可以看到为什么 网页配置
<configuration>
<connectionStrings>
<add
name="StoreContext"
connectionString="Data Source=ADMIN-PC\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;User ID=Login;Password=***********"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
global.asax
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Database.SetInitializer<Tutorial.Models.StoreContext>(null);
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
产品控制器
public class ProductController : Controller
{
StoreContext hello = new StoreContext();
//
// GET: /Product/
public ActionResult Index()
{
var product = hello.Product.ToList();
return View(product);
}
}
产品型号:
{
[Table("Product")]
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public double ProductPrice { get; set; }
}
}
StoreContext:
public class StoreContext: DbContext
{
public DbSet<Product> Product { get; set; }
}
【问题讨论】:
-
尝试从
Package Manager Console创建一个新的migration "stringName"和update-database,它们在您运行应用程序时必须匹配。 (我之所以这么说是因为错误:"Invalid object name 'dbo.Products' -
如何在包管理器中编写这个命令?
-
add-migration "stringNameOfWhatEverYouWantToCallThis"||||update-database(用户详细说明它在做什么)
标签: c# sql-server asp.net-mvc entity-framework entity-framework-migrations