簡體   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