我有一段代码需要根据数据库中的数据返回一个分隔字符串,除了提到注释的行之外,所有代码都运行良好。我知道单个 DbContext 不能在单个时间实例中用于多个 QUERIES 的事实。
private string FetchNewEmployees(DateTime addedAfter)
{
StringBuilder newEmployees = new StringBuilder();
using (MyDbContext dbContext = new MyDbContext())
{
var employees = dbContext.Student.Where(p => p.lastupdatedon > addedAfter);
foreach (var employee in employees)
{
newEmployees.Append(string.Format("{0}|{1}|{2}|{3}|{4}{5}",
employee.Name,
employee.DOB,
employee.department.DepartmentName, // This line throws error saying connection already open | commenting this makes it work like charm
employee.EMailAddress,
employee.SchoolName,
System.Environment.NewLine));
}
}
return newEmployees.ToString();
}
问题 id,“部门”是另一个表,因此是“员工”的外键......如果我不清楚,请告诉我。
现在的任何帮助都像是为我赢得了两个世界:)