使用方法Set(Type).Add(entity)在dbContext上设置身份ON [英] Set identity ON on dbContext using method Set(Type).Add(entity)
问题描述
键入entityType = Type.GetType(class);
object ob = db.Set(entityType).Create(entityType);
ob.GetMethod(set_Id)。Invoke(ob,new object [] {newId});
//...其他设置代码...
db.Set(entityType).Add(ob);
db.SaveChanges(); - 在此触发异常
但在SaveChanges启动异常
当IDENTITY_INSERT设置为OFF时,无法在表'TableName'
中插入标识列的显式值。
在分析器中,我看到我设置的id的标准插入批次。如何将实体对象添加到具有标识插入开的数据库,或者如何只保存新的entityObject?
实体框架假定整数主键是数据库生成的。如果您不希望使用属性 HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
或调用属性(e => e .EventID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
使用Fluent API。
您现在有一个问题,因为这仅仅是第一次工作。您将不得不放弃桌面或使用其他选项之一如何在实体框架代码中首次迁移时打开/关闭身份
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?
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
这篇关于使用方法Set(Type).Add(entity)在dbContext上设置身份ON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!