repository.InsertAsync 总是 returns entity.Id 0

repository.InsertAsync always returns entity.Id 0

有时我需要 Id 个插入的实体。为此,我使用:

entity = await _repository.InsertAsync(entity);

因此,entity.Id 始终为 0。因此,我在下面添加了这一行。

await CurrentUnitOfWork.SaveChangesAsync();

如果我添加这一行,我可以获得Id。但是,这种方式对我来说似乎很脏。还有别的办法吗?还是这种方式已经正确了?我只是想确定一下。我想知道使用 CurrentUnitOfWork 不会引起我可能不知道的问题。谢谢。

如果它是数据库中的标识列,id 是自动生成的,在行存储在数据库中之前,您无法获取 Id 值。

这就是您需要执行 SaveChangesAsync 的原因。在你这样做之前,对象在内存中但还没有存储在数据库中,这是为该对象分配 Id 的地方。

当您明确需要 Id 时,有 InsertAndGetIdAsync

var entityId = await _repository.InsertAndGetIdAsync(entity);