IDENTITY_INSERT ON error with foreign key

entity-framework entity-framework-6

Accepted Answer

The error message inside is false. Even when you are successful in turning on IDENTITY INSERT, EF continues to create an INSERT statement on the grounds that the IDENTITY column will provide the key value.

As a result, you must create an INSERT statement that contains the key value. Of course, you can also execute the INSERT command using.ExecuteSqlCommand(). Alternately, you may utilise EF to do the task, but you must use a model where the Entity doesn't contain keys created from a database. You cannot just include a switch into OnModelCreating since it only configures the model once per ModelType.

Instead, you may override the entity setting of the basic DbContext by creating a subtype of your DbContext for seeding. akin to this

class Db_Seed: Db
{
    public Db_Seed(string constr) : base(constr)
    {
        Database.SetInitializer<Db_Seed>(null);  //no initializer
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Customer>().Property(c => c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    }
}

Since the table does contain an IDENTITY, you must enable IDENTITY INSERT. However, in this situation, EF won't produce an INSERT statement that relies on the server to construct the key.

1
9/26/2018 1:08:46 PM


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