foreach循环中实体框架DbContext的using语句的使用



有一个解析器可以解析包含对象定义的文本文件。文本文件中的对象定义具有占位符句柄键。占位符句柄需要通过在DB中查找句柄值来替换为实际值。在我的应用程序中,我使用实体框架Core来处理DB。

解析器一次返回一个对象,我一次一个地在DB中查找句柄和其他属性。到目前为止,代码是这样的:

IEnumerable<ObjectInfo> GetNextContent();
IEnumerable<ObjectInfo> GetNextObjectInfo()
{
foreach (var item in parser.GetNextContent())
{
using (var dbContext = new ContentDbContext())
{
string key = item.Key;
string id = dbContext.Contents.Find(key).ObjectId;
item.Id = id;
// Assign other fields...
yield return item;
}
}
}

我的问题是,在上面的代码中,"using"块在foreach循环中。这样做对吗?另一个想法是,我可以在foreach循环之外使用"using"块,但我不确定代码中的迭代器会如何处理。

您应该将ContentDbContext移到外部以获得更好的性能。

这只是因为每个请求只需要一个context

每个web请求一个DbContext。。。为什么?

using (var dbContext = new ContentDbContext())
{
foreach (var item in parser.GetNextContent())
{
string key = item.Key;
string id = dbContext.Contents.Find(key).ObjectId;
item.Id = id;
// Assign other fields...
yield return item;
}
}

更新

你也可以加入,然后确保一次提取所有数据

// You need to fetch all `item.Key` from `parser.GetNextContent()` to get all data in `dbContext.Contents`
var keys = parser.GetNextContent().Select(p => p.Key).ToArray();
var result = (from content in dbContext.Contents 
join key in keys on content.Id equals key 
select new 
{
Id = content.ObjectId,
//....
}  

如果您使用的是C#8,使用的语句可能如下:

using var dbContext = new ContentDbContext();
foreach (var item in parser.GetNextContent())
{
string key = item.Key;
string id = dbContext.Contents.Find(key).ObjectId;
item.Id = id;
// Assign other fields...
yield return item;
}

最新更新