Autonumber with Entity Framework

前端 未结 3 1957
一个人的身影
一个人的身影 2020-11-27 17:26

I want to loop through a collection of objects and add them all to a table. The destination table has an auto-increment field. If I add a single object there is no problem

相关标签:
3条回答
  • 2020-11-27 17:41

    This happens because despite the auto-generated value of the column was created in the Database the EF never knew about it.

    So, in order to inform EF that the DB will handle the generated value you have to to open your edmx file (I always use the XML editor of VS to do this) and in the store schema definition language (SSDL) area, add the attribute StoreGeneratedPattern="Identity" to the column that needs the generated pattern. In this way EF reads the value generated in the DB and stores it in memory cache.

    Your entity type definition will look more or less like this:

     <EntityType Name="INVOICE">
              <Key>
                <PropertyRef Name="CODE" />
              </Key>
              <Property Name="CODE" Type="varchar" Nullable="false"
                  MaxLength="10" StoreGeneratedPattern="Identity"/>                 
     </EntityType>
    

    Be aware that if you happen to update your model all these changes will be lost and you'll have to repeat all the entire process.

    This works for EF 1.0, I'm not sure if in EF4 all these issues are already fixed.

    0 讨论(0)
  • 2020-11-27 17:54

    I'm using EF6, to set the StoreGeneratedPattern, you can also try open EDMX file in Visual Studio, right click on the Data Column in table and select Properties,

    Then you can set it from None to Identity in Properties Window:

    0 讨论(0)
  • 2020-11-27 17:57

    Set the StoreGeneratedPattern attribute to "Identity" in your SSDL for the autoincrement field. It should help.

    0 讨论(0)
提交回复
热议问题