ObjectContext.SaveChanges() violates primary key, throws UpdateException?

后端 未结 2 1755
深忆病人
深忆病人 2020-12-20 02:17

Paraphrasing from this MSDN documentation ...

An INSERT statement is generated by the Entity Framework and executed on the data source when SaveCh

相关标签:
2条回答
  • 2020-12-20 02:33

    This problem was caused by a bug in EF4 where the EF designer doesn't set the StoreGeneratedPattern attribute in the SSDL. The problem is documented in this blog and this Microsoft Connect ticket.

    The solution was to open my model's .edml file in a text editor, locate the <EntityType Name="student_term_data"> XML tag, and add StoreGeneratedPattern="Identity" to the property tag being used as an EntityKey:

      <EntityType Name="student_term_data">
         <Key><PropertyRef Name="id" /></Key>
         <Property Name="id" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
         ...
      </EntityType>
    

    I then re-opened my model in the EF designer, made a small change (moved an entity position) and saved. This caused the code generator to run, presumably synchronizing the CDSL with the SSDL.

    My code now runs as expected.

    0 讨论(0)
  • 2020-12-20 02:34

    EDIT

    If you are trying to do an insert, then do not fill in the PK field (I'm guessing that's StudentID).

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