ASP.NET MVC,实体框架代码优先,并致力于简单的HRM项目。
我的数据模型类:
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public List<Employee> Employees { get; set; }
}
我的上下文类:
public class HumanResourceContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
}
在我的家庭控制器Index
操作中生成数据库:
public ActionResult Index()
{
ViewBag.Message = "Welcome";
using (var context = new HR.DataModel.DAL.HumanResourceContext())
{
var query = from e in context.Employees select e;
foreach (HR.DataModel.Entities.Employee e in query)
{
ViewBag.Message += e.Name + ", ";
}
}
return View();
}
现在,当我运行此操作时,我收到此错误:
无法附加文件&#39; D:\ Projects \ HRSystem \ HR.Web \ App_Data \ HR.DataModel.DAL.HumanResourceContext.mdf&#39; as database&#39; HR.DataModel.DAL.HumanResourceContext&#39;。
我做错了什么?请帮忙。我试着找到解决方案。但是无法得到这个。感谢
答案 0 :(得分:0)
删除Initial Catalog
属性并添加已删除的attachdbfilename ex:
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-HR.Web-20151028044136.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
尝试更改名称<add name>
和一些与连接字符串相关的参考links