How to insert value for a identity column in Entity Framework?

c# entity-framework

Question

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.

1
0
3/24/2013 11:27:29 AM

Accepted Answer

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.

0
3/24/2013 10:56:19 AM

Popular Answer

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)



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