连接到数据库时出错

时间:2016-03-08 18:09:17

标签: c# entity-framework

我是Entity Framework的新手,在与数据库建立连接时我遇到了这个错误。

我的模特:

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; } } } 课程:

<connectionStrings>
    <add name="EmployeeContext" 
         connectionString="server=.;Database=TMA;Integrated Security=SSPI;" 
         providerName="System.Data.SqlClient" />

我想要连接到本地计算机的连接字符串和数据库名称TMA:

New-WebServiceProxy

但每当我运行此代码时,我都会收到此错误

  

&#34;创建模型时无法使用上下文。这个   如果在内部使用上下文,则可能抛出异常   OnModelCreating方法或者如果访问相同的上下文实例   并发多个线程。请注意DbContext的实例成员   并且不保证相关的类是线程安全的。&#34;

有人可以就此提供任何帮助吗?

非常感谢。

2 个答案:

答案 0 :(得分:3)

基于错误消息,听起来像context不能在这样的动作方法中使用 - 也许将它移动到类范围,就像大多数示例一样?

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
    {
        private readonly EmployeeContext db;

        public Employee1Controller()
        {
            db = new EmployeeContext();
        }

        // GET: Employee1
        public ActionResult Details(int id)
        {
            EmployeeModel employee = db.Employees.Single(emp => emp.EmployeeId == id);
            return View(employee);
        }
    }
}

答案 1 :(得分:1)

试试这个

<connectionStrings>
      <add name="EmployeeEntities" connectionString="Data Source=.;Initial Catalog=Employee;Integrated Security=True;" providerName="System.Data.SqlClient" />
      </connectionStrings>

EntityContext类

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 EntityContext:DbContext
    {
        public EntityContext()
        : base("EmployeeEntities")
    {
        //#if DEBUG 
        Database.SetInitializer<EntityContext>(new DatabaseInitializer());
        var ensureDLLIsCopied =
            System.Data.Entity.SqlServer.SqlProviderServices.Instance;
        //#endif
    }
        public DbSet<EmployeeModel> Employees { get; set; }
    }
}