Cannot insert explicit value for identity column in TABLE when IDENTITY_INSERT is set to OFF; .NET Core 2.1

.net c# entity-framework-core

Question

I'm trying to clone entities in EF Core. As far as I understand, I need to retrieve them AsNoTracking and then re-add them however when I do I get the error:

Cannot insert explicit value for identity column in Exercises when IDENTITY_INSERT is set to OFF;

I added the data annotation: [DatabaseGenerated(DatabaseGeneratedOption.Identity)] to the Id but I'm still getting the same error.

Here is my code:

public class Exercise : Entity
{
    public Exercise()
    {
        Sets = new HashSet<Set>();
    }       

    public DateTime Date { get; set; }

    public int MuscleGroupId {get;set;}

    public int MesoId { get; set; }

    public ICollection<Set> Sets { get; set; }

    public void AddSet(Set set)
    {
        Sets.Add(set);
    }
}

And here is my code for Entity which has I set an annotation telling EF Core the ID is database generated:

 public class Entity
 {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
 }

Here is the code to clone the entities:

 var exercises = _context.Exercises.AsNoTracking().Include(y => y.Sets)
.Where(x => x.MesoId == mesoId && x.Date == fromDate);

 foreach (var exercise in exercises)
   {
      exercise.Date = toDate;
      _context.Exercises.Add(exercise);
   }

 await _context.SaveChangesAsync();
1
1
9/8/2019 12:10:38 AM

Popular Answer

You cannot store values into an Identity column in the database because that value is managed by the database itself.

When "cloning" your Exercise records you need to set Id=0 so that when the new row gets inserted the database will create the Identity value for it, e.g.:

foreach (var exercise in exercises)
{
   exercise.Date = toDate;
   exercise.Id = 0; //<<--This is important!
   _context.Exercises.Add(exercise);
}
await _context.SaveChangesAsync();
0
9/8/2019 4:05:46 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow