Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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); } 
like image 345
lucacelenza Avatar asked Feb 27 '17 08:02

lucacelenza


2 Answers

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); } 
like image 178
lucacelenza Avatar answered Sep 19 '22 16:09

lucacelenza


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; } } 
like image 27
Yashveer Singh Avatar answered Sep 19 '22 16:09

Yashveer Singh