[英]How to insert value for a identity column in Entity Framework?
I've created two columns in sql table that one is a identity column and another one is a varchar column. 我在sql表中创建了两列,一列是标识列,另一列是varchar列。 I need to generate identity column starting from the value 1000. I had tried the below code snippet, but it was given error "An error occurred while updating the entries. See the inner exception for details.." 我需要从值1000开始生成标识列。我尝试了下面的代码段,但收到错误消息“更新条目时发生错误。有关详细信息,请参阅内部异常。”
Place objPlace = new Place();
objPlace.PNAME = "place 3";
//objPlace.PID = 1003; //purposefully commented for auto increment
objContext.Places.AddObject(objPlace);
objContext.SaveChanges();
I guess this is very basic question as I'm new to EF so please help me to sort it out. 我想这是一个非常基本的问题,因为我是EF新手,所以请帮助我进行梳理。
Are you just wanting to do this in EF to learn the syntax? 您是否只是想在EF中学习语法? the reason I ask, is because you could set the seed on the column in SSMS ( http://msdn.microsoft.com/en-gb/library/aa933196%28v=sql.80%29.aspx ) 我问的原因是因为您可以在SSMS的列上设置种子( http://msdn.microsoft.com/en-gb/library/aa933196%28v=sql.80%29.aspx )
You cannot assign value to the Identity column. 您不能将值分配给“标识”列。 its meaningless. 它毫无意义。
if you want to change the starting value of your identity column, why not do it through a simple script? 如果要更改标识列的起始值,为什么不通过简单的脚本来更改呢?
context.Database
.ExecuteSqlCommand("ALTER TABLE Place ALTER COLUMN Id IDENTITY (1000,1)");
this will insert Place.Id
as 1000, for the first row in the table, and then 1001,1002... and so on for subsequent rows. 这将在表的第一行中插入Place.Id
为1000,然后在表的第一行中插入1001,1002 ...,依此类推。
Let sql server generate identity. 让sql server生成身份。 Set values for identity seed and Identity increment. 设置标识种子和标识增量的值。
When column is identity , inserting record from entity framework will raise following error. 当column为identity时,从实体框架插入记录将引发以下错误。 Cannot insert explicit value for identity column in table 'MY_ENTITY' when IDENTITY_INSERT is set to OFF. 当IDENTITY_INSERT设置为OFF时,无法为表'MY_ENTITY'中的Identity列插入显式值。 To avoid error set entity property StoreGeneratedPattern="Identity" 为了避免错误设置实体属性StoreGeneratedPattern =“ Identity”
<EntityType Name="MY_ENTITY">
<Key>
<PropertyRef Name="UserID" />
</Key>
<Property Name="RecordID" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.