none
Entity Framework 5 entity key RRS feed

  • Question

  • Hi guys,

    When I add an entity, it's key takes the value 5.

    Then when I remove it and add another new entity, it takes the key 6, not 5 as I want !

    How can I fix that ?

    Monday, March 4, 2013 10:00 AM

Answers

  • Hi Houssem;

    It sounds like the database is generating the primary key and that identity property is set to true. This will create a new key value incremented by the value in the column property "identity increment" for the column which seems to be set to 1. This is by design, when SQL server adds a new record it will use the last value used plus the identity increment value. It will not use any previous value that was deleted. Entity Framework when you create a new entity in code assigns the value 0 to this primary key and when you do a SaveChanges method call the database will update the primary key and sends that back to the Entity Framework and EF will update the local copy of the record.

      


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Monday, March 4, 2013 2:00 PM

All replies

  • Hi Houssem;

    It sounds like the database is generating the primary key and that identity property is set to true. This will create a new key value incremented by the value in the column property "identity increment" for the column which seems to be set to 1. This is by design, when SQL server adds a new record it will use the last value used plus the identity increment value. It will not use any previous value that was deleted. Entity Framework when you create a new entity in code assigns the value 0 to this primary key and when you do a SaveChanges method call the database will update the primary key and sends that back to the Entity Framework and EF will update the local copy of the record.

      


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Monday, March 4, 2013 2:00 PM
  • Thank you Fernando Soto for the nice explanation !
    Monday, March 4, 2013 4:31 PM