Can't auto-generate IDENTITY with AddRange in Entity Framework

后端 未结 4 1523

I don\'t know if it\'s an Entity Framework\'s desing choice or a wrong approach on my behalf, but whenever I try to AddRange entities to a DbSet I can\'t seem to get the aut

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-07 22:18

    What was causing the problem? Enumerables! Take a look at the EDIT section in my question for the solution.

    EDIT: posting the updated code here as answer. The problem was in the way I used enumerables. Bottom line is you should never trust lazy loading when you need consistent results right away.

    public class Request
    {
        public string Field { get; set; }
    
        public Entity ToEntity()
        {
            return new Entity() { Field = Field };
        }
    }
    
    public async Task> SaveRequests(IEnumerable requests)
    {
        var entities = requests.Select(r => r.ToEntity()); //not working
        var entities = requests.Select(r => r.ToEntity()).ToArray(); //working
    
        _dbContext.Entities.AddRange(entities);
        await _dbContext.SaveChangesAsync();
    
        return entities.Select(e => e.Id);
    }
    

提交回复
热议问题