问题
I'm trying save entity to db using dbContext.
Type entityType = Type.GetType("class");
object ob = db.Set(entityType).Create(entityType);
ob.GetMethod("set_Id").Invoke(ob, new object[] { newId });
//...other set code...
db.Set(entityType).Add(ob);
db.SaveChanges(); -- here fires exception
But after SaveChanges fire the Exception
"Cannot insert explicit value for identity column in table 'TableName' when IDENTITY_INSERT is set to OFF".
In the profiler I see the standard insert batch with the id I set. How can I add entity object to db with identity insert ON or how can I just save the new entityObject?
回答1:
Entity Framework assumes that integer primary keys are database generated. If you don't want that you have to turn it off with the attribute HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
or calling Property(e => e.EventID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
using the Fluent API.
You now have a problem because this only works first time around. You will have to drop the table or use one of the other options here how to switch identity on/off in entity framework code first migrations
回答2:
It seems you have a table definition that says the database should inserts ID's and not allow the application to do this. At the same time an entity-framework layout that tries to insert values for id's.
You can allow the application to insert ID's by using this: http://technet.microsoft.com/en-us/library/aa259221(v=sql.80).aspx to allow it.
The question is do you really want to allow that applications can choose their own IDs? Or do you want to let the database decide?
In this case you should check the properties in your dbml file. The column Id should have a property "Auto Generated Value". It has to be set to True.
来源:https://stackoverflow.com/questions/19311135/set-identity-on-on-dbcontext-using-method-settype-addentity