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

后端 未结 4 1553

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:17

    In Entity Framework Core using Code First, I got this to work by doing two things:

    1. I added the [DatabaseGenerated(DatabaseGeneratedOption.Identity)] decorator to the Entity's Primary Key, like Yashveer Singh's answer stated
    2. I set the new entity object's primary key to 0

    After performing those two steps, I didn't need to convert IEnums to Arrays. I was simply able to run:

    _dbContext.Entities.AddRange(entities);
    await _dbContext.SaveChangesAsync();
    

提交回复
热议问题