C# repository.InsertAsync始终返回实体Id 0

C# repository.InsertAsync始终返回实体Id 0,c#,asp.net,entity-framework-6,aspnetboilerplate,C#,Asp.net,Entity Framework 6,Aspnetboilerplate,有时我需要插入实体的Id。为了实现这一点,我使用: entity = await _repository.InsertAsync(entity); 这样,entity.Id始终为0。因此,我在下面添加了一行 await CurrentUnitOfWork.SaveChangesAsync(); 如果我添加此行,我可以获得Id。但是,我觉得这种方式很肮脏。还有别的办法吗?或者这种方式已经正确了?我只是想确定一下。我想知道使用CurrentUnitOfWork不会导致我不知道的问题。谢谢。如果它

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

entity = await _repository.InsertAsync(entity);
这样,
entity.Id
始终为0。因此,我在下面添加了一行

await CurrentUnitOfWork.SaveChangesAsync();

如果我添加此行,我可以获得
Id
。但是,我觉得这种方式很肮脏。还有别的办法吗?或者这种方式已经正确了?我只是想确定一下。我想知道使用
CurrentUnitOfWork
不会导致我不知道的问题。谢谢。

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


这就是为什么需要执行SaveChangesAsync。在执行此操作之前,对象位于内存中,但尚未存储在DB中,在DB中将为该对象分配Id

当您明确需要
Id
时,可以使用
InsertAndGetIdAsync

var entityId = await _repository.InsertAndGetIdAsync(entity);