我一直在使用Model和DB First创建基于ASP.NET MVC的项目。这次我必须使用Code First方法。我已经阅读了几个教程,现在我想测试一下。但得到错误'不知道为什么。 这是我的模特课:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public string Email { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
这是上下文类:
public class CompanyEntities:DbContext
{
public CompanyEntities()
: base("name=CompanyEntities")
{
}
public virtual DbSet<Employee> Employees { get; set; }
}
这是我的连接字符串:
<connectionStrings>
<add name="CompanyEntities" connectionString="Data Source=MOON\SQLSERVER;Initial Catalog=c1;Persist Security Info=True;User ID=sa;Password=pppppp" providerName="System.Data.EntityClient" />
这是Employees控制器的操作方法:
public ActionResult Index()
{
try
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<CompanyEntities>());
return View(db.Employees.ToList());
}
catch (Exception)
{
throw;
}
}
当我调用/ Employees / Index操作时,我收到此错误:“MvcCompanyCF.dll中发生了'System.ArgumentException'类型的异常,但未在用户代码中处理”。其他信息:不支持关键字:'数据源'。
提前致谢。
答案 0 :(得分:0)
在初始化Context对象之前,应保留 Database.SetInitializer()方法。在ASP.NET Web应用程序中,最佳位置是Global.asax文件的Application_Start()事件。
参考:http://www.codeproject.com/Tips/814618/Use-of-Database-SetInitializer-method-in-Code-Firs
答案 1 :(得分:0)
在您的web.config中,您必须首先使用providerName="System.Data.SqlClient"
代码。