简体   繁体   中英

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. 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.."

   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.

Are you just wanting to do this in EF to learn the syntax? 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 )

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.

Let sql server generate identity. Set values for identity seed and Identity increment.

When column is identity , inserting record from entity framework will raise following error. Cannot insert explicit value for identity column in table 'MY_ENTITY' when IDENTITY_INSERT is set to OFF. To avoid error set entity property StoreGeneratedPattern="Identity"

  <EntityType Name="MY_ENTITY">
              <Key>
                <PropertyRef Name="UserID" />
              </Key>
              <Property Name="RecordID" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />

The ExecuteSqlCommand() command mentioned in above post will not work as mentioned in the link

Aother solution is mentioned the here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM