In Entity Framework, getting the value of an identity column after inserting

nima picture nima · Jun 10, 2011 · Viewed 29.4k times · Source

I'm using EF4. I want to insert a new MyObject into the database. MyObject has two fields:

Id: int (Identity) and Name: string

As I've seen in documentation Entity Framework is supposed to set MyObject.Id to the value generated by database after the call to SaveChanges() but in my case that doesn't happen.

using (var context = new MyEntities())
{
    var myObject = MyObjects.CreateMyObject(0, "something"); // The first parameter is identity "Id"
    context.MyObjects.AddObject(myObject);
    context.SaveChanges();
    return myObject.Id; // The returned value is 0
}

UPDATE:

This happens in one of my entities and others work fine. By the way, I checked and the DB column is identity and StoreGeneratedPattern is set to Identity. Here is the SSDL. I don't see any difference. The first one isn't working right:

    <EntityType Name="OrgUnit">
      <Key>
        <PropertyRef Name="Srl" />
      </Key>
      <Property Name="Srl" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
      <Property Name="TypeId" Type="smallint" Nullable="false" />
      <Property Name="Name" Type="varchar" Nullable="false" MaxLength="80" />      
    </EntityType>

    <EntityType Name="OrgType">
      <Key>
        <PropertyRef Name="Srl" />
      </Key>
      <Property Name="Srl" Type="smallint" Nullable="false" StoreGeneratedPattern="Identity" />
      <Property Name="Title" Type="varchar" Nullable="false" MaxLength="120" />
      <Property Name="Options" Type="int" Nullable="false" />
    </EntityType>

The update is done successfully in the database and the identity is generated but the entity object is not updated with the new identity.

Answer

marc_s picture marc_s · Jun 10, 2011

In that case, you EF model is probably not up to date - EF should automagically get your new ID from the database. Try refreshing your EF model.

Your identity column's properties should look like this in your EDMX model:

enter image description here