且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在实体框架中,插入后获取标识列的值

更新时间:2023-02-05 08:01:18

哇!那是一场噩梦,但终于解决了,虽然我不明白问题是什么。也许这有助于有同样问题的人。


  1. 生成用于创建表及其数据的脚本。


  2. 运行脚本。


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.

wow! that was a nightmare but at last I solved it, although I didn't understand what the problem was. Maybe this helps someone with the same problem.

  1. Generate the script for creating the table and its data.
  2. Drop the table.
  3. Run the script.