Adding objects using the AddRange method does not update the object id
I am using EF Core 1.1.1
. I noticed when I add IEnumerable<Entity>
using a method AddRange
and then call SaveChanges()
, then the entities are persisted in the database, however their id is not updated.
The code below does not update the ID after SaveChanges (). Note that I am passing requests asIEnumerable
public async Task Post([FromBody]IEnumerable<string> values)
{
var requests = values.Select(x => new Test()
{
Name = x,
Status = "Init"
});
await _dbContext.Tests.AddRangeAsync(requests).ConfigureAwait(false);
await _dbContext.SaveChangesAsync().ConfigureAwait(false);
foreach (var r in requests)
{
var id = r.ID;
}
}
The code below does not update the id after SaveChanges (). Note that I am passing request.ToList()
as a parameter to the methodAddRange
public async Task Post([FromBody]IEnumerable<string> values)
{
var requests = values.Select(x => new Test()
{
Name = x,
Status = "Init"
});
await _dbContext.Tests.AddRangeAsync(requests.ToList()).ConfigureAwait(false);
await _dbContext.SaveChangesAsync().ConfigureAwait(false);
foreach (var r in requests)
{
var id = r.ID;
}
}
The code below makes the ID update after SaveChanges (). Note. I call ToList()
after picking values.
public async Task Post([FromBody]IEnumerable<string> values)
{
var requests = values.Select(x => new Test()
{
Name = x,
Status = "Init"
}).ToList(); //<------ ToList() or ToArray() would work
await _dbContext.Tests.AddRangeAsync(requests).ConfigureAwait(false);
await _dbContext.SaveChangesAsync().ConfigureAwait(false);
foreach (var r in requests)
{
var id = r.ID;
}
}
I'm not sure if this is a bug in EF, or how this is supposed to work. I understand that IEnumerable
is lazy
and List
and Array
are eager
, but if the method AddRange
takes IEnumerable
as a parameter, then it should work independently.
source to share
No one has answered this question yet
See similar questions:
or similar: