repository.InsertAsync 总是返回 entity.Id 0

Taş*_*şah 0 c# asp.net entity-framework-6 aspnetboilerplate

有时我需要Id插入实体。为了实现这一点,我使用:

entity = await _repository.InsertAsync(entity);
Run Code Online (Sandbox Code Playgroud)

有了这个,entity.Id总是 0。因此,我在下面添加了一行。

await CurrentUnitOfWork.SaveChangesAsync();
Run Code Online (Sandbox Code Playgroud)

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

aar*_*ron 5

还有InsertAndGetIdAsync当你明确需要的Id

var entityId = await _repository.InsertAndGetIdAsync(entity);
Run Code Online (Sandbox Code Playgroud)