Bv2*_*202 6 c# entity-framework
我有一个父实体,具有子实体的导航属性。只要子实体中存在关联记录,父实体就不能被删除。子实体可以包含数十万条记录。
我想知道在实体框架中最有效的做法是什么:
var parentRecord = _context.Where(x => x.Id == request.Id)
.Include(x => x.ChildTable)
.FirstOrDefault();
// check if parentRecord exists
if (parentRecord.ChildTable.Any()) {
// cannot remove
}
Run Code Online (Sandbox Code Playgroud)
或者
var parentRecord = _context.Where(x => x.Id == request.Id)
.Select(x => new {
ParentRecord = x,
HasChildRecords = x.ChildTable.Any()
})
.FirstOrDefault();
// check if parentRecord exists
if (parentRecord.HasChildRecords) {
// cannot remove
}
Run Code Online (Sandbox Code Playgroud)
第一个查询可能包含数千条记录,而第二个查询则不会,但是第二个查询更复杂。
哪种方法最好?
我想说这要看情况。这取决于您使用的 DBMS。这取决于优化器的工作效果等。因此,带有 JOIN 的单个语句可能比许多 SELECT 语句快得多。
一般来说,我会说当您需要子表中的行时使用.Include(). 否则不包括它们。或者简单来说,就是读取你需要的数据。
| 归档时间: |
|
| 查看次数: |
3892 次 |
| 最近记录: |