While creating application with c# + entity framework 6 (database first) + sql server I got next problem:
Cannot insert explicit value for identity column in table 'Qualification' when IDENTITY_INSERT is set to OFF.
I've tried to google my problem and the most popular answer was just to add attribure to model
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
But it doesn't help. Then I decided to run SQL command "SET IDENTITY_INSERT dbo.Qualification ON", but it didn't help as well. In my db (I use management studio) Identity Specification (Is Identity) set to TRUE
There is my entity generated by .NET:
public partial class Qualification
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Qualification()
{
this.Trainer = new HashSet<Trainer>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Trainer> Trainer { get; set; }
}
And my context class:
public partial class SportClubContext : DbContext
{
public SportClubContext()
: base("name=SportClubContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<sysdiagrams> sysdiagrams { get; set; }
public virtual DbSet<Client> Client { get; set; }
public virtual DbSet<Group> Group { get; set; }
public virtual DbSet<Qualification> Qualification { get; set; }
public virtual DbSet<Schedule> Schedule { get; set; }
public virtual DbSet<Trainer> Trainer { get; set; }
public virtual DbSet<Training> Training { get; set; }
}
And the way how I try to add new record to my db:
var qualification = new Qualification
{
Name = textBox1.Text
};
context.Qualification.Add(qualification);
await context.SaveChangesAsync();