繁体   English   中英

从MVC .net应用程序使用Entity Framework连接到SQL数据库时出错

[英]Error connecting to SQL database with Entity Framework from MVC .net application

我收到以下错误消息: 提供程序:SQL网络接口,错误:26-指定服务器/实例时出错

我所做的是创建一个继承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; }
}

在控制器类中我编码:

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

然后,使用服务器资源管理器中的选项连接到服务器和数据库。 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" />

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

网站的网址也输入正确:/ localhost / {projectName} / Employee / EmployeeList / 1

其中1是我用于Employee控制器中的操作方法EmployeeList的id参数。

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

从服务器浏览器的屏幕截图中: 服务器浏览器

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

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

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

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

注意 :您还可以通过右键单击数据库节点,然后单击“修改连接”,获得“服务器资源管理器”窗口,以为您提供正在查看的数据库的连接字符串。 单击“高级”,连接字符串值将显示在“数据源”值下。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM