Entity Framework 7 - SET IDENTITY_INSERT skips entity id mapping - Fails to insert values

111 Views Asked by At

I have a simple Entity Class as under:

[Table("Grade")]
public class Grade
{
    //Tried changing this annotation to Identity
    //[DatabaseGenerated(DatabaseGeneratedOption.None), Key]
    [Key]
    public int GradeId { get; set; }
    public string GradeName { get; set; }
}

I am trying to seed this with EF7 and CSVHelper for DNX 5 project I am working, as under

using (StreamReader reader = new StreamReader(fs, System.Text.Encoding.UTF8, false)){
CsvReader csvReader = new CsvReader(reader);
IEnumerable<Grade> grades = csvReader.GetRecords<Grade>();

using (_context.Database.BeginTransaction()) 
{
_context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [dbo].[Grade] ON");
_context.Grades.AddRange(grades);
_context.SaveChanges();
_context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [dbo].[Grade] OFF");
}}

If I comment the using (_context.Database.BeginTransaction()) line error for IDENTITY_INSERT OFF appears though code gets compiled

However with the BeginTransaction() the following error appears

enter image description here

CSV File used for this project (CSVReader is working fine- returning all columns and data as shown under)

enter image description here

enter image description here

What could I be doing wrong?

0

There are 0 best solutions below