I am using VS 2015 to create an ASP.NET MVC project and found the following error:
Cannot attach the file 'F:\MINH\Documents\Visual Studio 2015\Projects\NailShop\NailShop\App_Data\NailShop.Models.TechnicianContext.mdf' as database 'NailShop.Models.TechnicianContext'.
The error is found in the line:
technicianDetails = technicianContext.Technician.Single(x => x.TechnicianID == id);
I see that in Project Explorer/App_Data folder is empty. I didn't delete and thing. This is a fresh project.
My model:
namespace NailShop.Models
{
[Table("TechnicianDetails")]
public class TechnicianDetails
{
// model fields:
[Key]
public int TechnicianID { get; set; } // no semicolon
public int commentID { get; set; }
public int serviceID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string introduction { get; set; }
public int rating { get; set; }
}
}
My controller:
public class TechnicianDetailsController : Controller
{
// GET: TechnicianDetails
public ActionResult TechnicianDetails(int id)
{
// Model class:
TechnicianDetails technicianDetails = new Models.TechnicianDetails();
// DBContext class:
TechnicianContext technicianContext = new TechnicianContext();
// map the row in database table to model : assign the TechnicianID in the db to the parameter technicianID of the action method
technicianDetails = technicianContext.Technician.Single(x => x.TechnicianID == id);
return View("~/Views/Technician/TechnicianDetails.cshtml", technicianDetails);
}
}
My connection string: I assign the connection string by Server Explorer -> Add Connection --> select the server and database --> Advanced --> copy and paste the Data Source. The database is also connectable via Visual Studio Server Explorer
Package manager console:
I followed the steps from Cannot attach the file *.mdf as database and choose the guide "to fix it with SQL Server Management Studio".
I also followed the steps from: Cannot attach the file .mdf as database
I run
SQLLocalDB info
and found 2 instances:
MSSQLLocalDB
ProjectsV12
I then followed to stop, delete, start each instance.
I also ran update-database
and get the following error:
I found out the name of the connection string (TechnicianDetailContext) doesn't match with the class inheritting DBContext class that I created (TechnicianContext).
Therefore, Visual Studio will run the TechnicianContext with defaul connection, that points to a different local server as show in attach image:
enter image description here