gpt4 book ai didi

c# - 连接数据库时出错

转载 作者:行者123 更新时间:2023-11-30 20:37:35 26 4
gpt4 key购买 nike

我是 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;}
}
}

我的 Controller :

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" />

但是每当我运行这段代码时,我都会收到这个错误

"The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe."

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

非常感谢。

最佳答案

根据错误消息,听起来 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);
}
}
}

关于c# - 连接数据库时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35874789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com