'it does not exist or you do not have permissions when executing SQL IDENTITY_INSERT

I want to turn on IDENTITY_INSERT before inserting data into the database. But when I run my code it throws an error

"Cannot find the object "UniversityDB.StudentRegistrationModels" because it does not exist or you do not have permissions"

My control code is:

public ActionResult Create([Bind(Include = "StudentId,CourseId,IsPaymentComplete")] StudentRegistrationModels studentRegistration)
{
    using (var db = new UniversityDBContext())
    {
        db.StudentRegistration.Add(studentRegistration);
        db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT UniversityDB.StudentRegistrationModels ON;");
        db.SaveChanges();
        db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT UniversityDB.StudentRegistrationModels OFF");
    }
}

and database model is:

public class StudentRegistrationModels
{
    [Key, ForeignKey("Student"), Required]
    public int StudentId { get; set; }
    [ForeignKey("Course"), Required]
    public int CourseId { get; set; }
    public DateTime EnrollDate { get; set; }
    public bool IsPaymentComplete { get; set; }
    public virtual StudentModel Student { get; set; }
    public virtual CourseModels Course { get; set; }
    
}

Please help me to fix it



Solution 1:[1]

If something wrong in turn on/off IDENTITY_INSERT, The error message will be: Cannot insert explicit value for identity column in table 'xxxxxxx' when IDENTITY_INSERT is set to OFF.

But your error message is not that. So I presume that UniversityDB.StudentRegistrationModels doesn't map correctly to a table in your database.

You can try to modify your code in the following format:

SET IDENTITY_INSERT [ [ database_name . ] schema_name . ] table_name { ON | OFF }

database_name Is the name of the database in which the specified table resides.

schema_name Is the name of the schema to which the table belongs.

table_name Is the name of a table with an identity column.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Xinran Shen