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 auto-generated IDENTITY fields.
[Table("entities")] public class Entity { [Key] [Column("id")] public long Id { get; set; } [Column("field")] public string Field { get; set; } } var entities = new Entity[] { new Entity() { Field = "A" }, new Entity() { Field = "B" }, }; _dbContext.Entities.AddRange(entities); await _dbContext.SaveChangesAsync(); //ids are still default(long) at this point!!
EDIT: Here's the updated code to show what was causing the problem: enumerables. No need to add other attributes to the entity classes.
public class Request { public string Field { get; set; } public Entity ToEntity() { return new Entity() { Field = Field }; } } public async Task<IEnumerable<long>> SaveRequests(IEnumerable<Request> 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); }
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<IEnumerable<long>> SaveRequests(IEnumerable<Request> 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); }
Please try this, it works for Int type column, need to try on long types.
[Table("entities")] public class Entity { [Key] [Column("id")] // this you need to tell to Ef to use Identity . [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long Id { get; set; } [Column("field")] public string Field { get; set; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With