我是Entity Framework的新手,在與數據庫建立連接時出現此錯誤。連接到數據庫時出現錯誤
我的模型:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace MVCTest.Models
{
[Table("Employee")]
public class EmployeeModel
{
public int EmployeeId { get; set; }
public string name {get;set;}
}
}
我的控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCTest.Models;
namespace MVCTest.Controllers
{
public class Employee1Controller : Controller
{
// GET: Employee1
public ActionResult Details(int id)
{
EmployeeContext employeecontext = new EmployeeContext();
EmployeeModel employee= employeecontext.Employees.Single(emp => emp.EmployeeId == id);
return View(employee);
}
}
}
我EmployeeContext
類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.Core.EntityClient;
namespace MVCTest.Models
{
public class EmployeeContext:DbContext
{
public DbSet<EmployeeModel> Employees { get; set; }
}
}
,我想連接到我的本地計算機和數據庫名稱我的連接字符串TMA:
<connectionStrings>
<add name="EmployeeContext"
connectionString="server=.;Database=TMA;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
但每當我運行這段代碼我收到此錯誤
「上的環境不能被創建的模型,同時使用。如果在 OnModelCreating方法中使用上下文,或者同時由多個線程訪問同一上下文實例,則可能會拋出此 異常。需要注意的DbContext 及相關類中的實例成員不能保證是線程安全的。」
誰能請提供有關這個任何幫助嗎?
非常感謝。
'服務器=;'應該是問題,如果你想使用的LocalDB將其更改爲'(的LocalDB)\ 11.0;'[參考](https://msdn.microsoft.com/en-us/library/jj653752(v = vs.110).aspx) –
您使用普通SQL Server還是Express?如果Express,'.'對連接字符串的服務器部分聽起來不正確,並且您應該使用'。\ SQLEXPRESS'(或'(localdb)'或類似的名稱) – Jcl