错误连接到SQL数据库与实体框架从MVC .NET应用程序

问题描述:

我有以下错误信息:provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified错误连接到SQL数据库与实体框架从MVC .NET应用程序

我所做的是创建一个模型类,继承DbContext类:

class EmployeeContext : DbContext 
{ 
    public DbSet<Employee>Employees { get; set; } 
} 

和创建另一个模型类:

[Table("EmployeeList")] 
public class Employee 
{ 
    public int EmployeeID { get; set; }   // no semi-colon 
    public string firstName { get; set; } 
    public string lastName { get; set; } 
    public string position { get; set; } 
} 

,并在控制器的I类编码:

public class EmployeeController : Controller 
{ 
    public ActionResult EmployeeList(int id) 
    { 
     Employee employee = new Employee();   //instantiate the object of model class to be use 
     EmployeeContext employeecontext = new EmployeeContext(); //create context model class 
     // assign the value of the context model object that is mapped to database     
     employee = employeecontext.Employees.Single(x => x.EmployeeID == id);  
     return View("EmployeeDetail", employee); // include view name, object of model class 
    } 
} 

然后我使用Server Explorer中的选项连接到服务器和数据库。 2

我补充与我前面创建的DbContext类名称相关联的连接字符串:

<add name="EmployeeContext" 
    connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnet-MVCDemo-20161213044601.mdf;Initial Catalog=aspnet-MVCDemo-20161213044601;Integrated Security=True;User Instance=True" 
    providerName="System.Data.SqlClient" /> 

服务器进行检查,以允许远程连接,从本地数据库中运行。

网站URL也正确地键入:/本地主机/ {PROJECTNAME} /雇员/ EmployeeList的/ 1

其中1是,我使用的在Employee控制器的动作方法EmployeeList id参数。

您的连接字符串指向SQL Server的SQL Express实例,而不是您的实际数据库服务器。 Data Source=.\SQLEXPRESS

从你的服务器资源管理器的截图: server explorer

您的连接字符串的数据源组件应Data Source=.\sqlserver2014

更新:重读你的问题后,我意识到,不仅仅是你的数据源错了。您的连接字符串甚至没有指向正确的数据库“MVCDemo”。

完整的连接字符串包括基于截图正确的初始目录:

<add name="EmployeeContext" connectionString="Data Source=.\sqlserver2014;Initial Catalog=MVCDemo;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" /> 

注意:你也可以在服务器资源管理器窗口,让您的数据库连接字符串被查看,通过右键点击数据库节点,然后在修改连接上。点击高级,连接字符串值将显示在数据源值下。

+0

连接字符串是我的问题的来源是绝对正确的,并且您的建议可以帮助我解决问题。非常感谢 ! 我在修复后出现了另一个问题(错误:用户'IIS APPPOOL \ DefaultAppPool'登录失败。)但是,使用IIS express而不是本地IIS的更改完全可以解决问题。 –

+0

@MinhPham,很高兴听到。由于您是*的新手,请参阅[我应该怎么做,当有人回答我的问题?](http://*.com/help/someone-answers)接下来应该做什么。 – Adrian