无法将mdf文件附加为数据库

时间:2016-12-29 04:31:55

标签: sql-server asp.net-mvc database mdf

我使用VS 2015创建ASP.NET MVC项目并发现以下错误:

  

无法将文件'F:\ MINH \ Documents \ Visual Studio 2015 \ Projects \ NailShop \ NailShop \ App_Data \ NailShop.Models.TechnicianContext.mdf'附加为数据库'NailShop.Models.TechnicianContext'。

错误可在以下行中找到:

technicianDetails = technicianContext.Technician.Single(x => x.TechnicianID == id);

我在Project Explorer / App_Data文件夹中看到它是空的。我没有删除和东西。这是一个新项目。

我的模特:

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; }
    }
}

我的控制器:

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);
    }
}

我的连接字符串:我通过服务器资源管理器分配连接字符串 - >添加连接 - >选择服务器和数据库 - >高级 - >复制并粘贴数据源。该数据库也可通过Visual Studio Server Explorer连接

enter image description here

包管理器控制台:

我按照Cannot attach the file *.mdf as database中的步骤操作,然后选择“使用SQL Server Management Studio修复它”的指南。

我还按照以下步骤进行操作:Cannot attach the file .mdf as database

我跑

SQLLocalDB info

并找到了2个实例:

MSSQLLocalDB
ProjectsV12

然后我跟着停止,删除,启动每个实例。

我还运行update-database并收到以下错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

我发现连接字符串的名称( TechnicianDetailContext )与继承我创建的DBContext类的类( TechnicianContext )不匹配。

因此,Visual Studio将使用默认连接运行TechnicianContext,该连接指向附加图像中显示的其他本地服务器:

enter image description here