I use the following code to insert a collection of entities into by DB using EntityFrameworkCore.SqlServer (7.0.7). I expect that my returned entities are set with an auto generated id which is a int identity(1,1) not null.
public async Task<IEnumerable<Instrument>> CreateAsync(IEnumerable<Instrument> instruments)
{
await DbContext.AddRangeAsync(instruments);
foreach (Instrument entity in instruments)
{
var entityEntry = DbContext.Entry(entity);
Debug.WriteLine($"Entity State: {entityEntry.State}");
}
await DbContext.SaveChangesAsync();
return instruments;
}
the foreach loop has just been added to check the entity state which is detached . I tried also using DbContext.AddRange(instruments) instead of the async version and the entities are still detached and the id are not set. However if I iterate over my entity and call the following code on each indiviual entity, the is is set with a value:
public async Task<Instrument> SaveAsync(Instrument entity)
{
if (entity.InstrumentId <= 0)
await DbContext.AddAsync(entity);
else
DbContext.UpdateRange(entity);
await DbContext.SaveChangesAsync();
return entity;
}
For what I know, calling AddRangeAsync should attach my entities to the context and set the value of my primary key for each entities. Has someone an idea or faced the same behaviour? Also is my code correct to add new entities into the db? Thanks for the help