IDENTITY INSERT and LINQ to SQL

后端 未结 6 1319
难免孤独
难免孤独 2020-12-03 08:04

I have a SQL Server database. This database has a table called Item. Item has a property called \"ID\". ID is the primary key on my table. This primary key is an int with a

相关标签:
6条回答
  • 2020-12-03 08:39

    Set the "Auto Generated" property of the ID Property to "True".

    0 讨论(0)
  • 2020-12-03 08:41

    The ID will be zero until you call context.SubmitChanges();. Step through the code and look at the value after SubmitChanges has been invoked. Remember, the DB is actually assigning the ID (assuming that it's a auto-increment key).

    Take a look at this:

    Working with Entity Keys

    0 讨论(0)
  • 2020-12-03 08:42

    The simplest way is: 1. open dbml 2. Select class for inserting 3. Select column with primary-key 4. check Auto Generated Property in properties window (it should be set to True)

    0 讨论(0)
  • 2020-12-03 08:54

    You must define in your mapping that id is generated in the database. The way to do this depends on the type of mapping you are using. if you are using code attributes make sure that you specify IsDbGenerated in the ColumnAttribute for the Id property (or in XML mapping). if you are using dbml file make sure that Auto Generated Value is set to true.

    0 讨论(0)
  • 2020-12-03 08:56

    It sounds simply as though your model is unaware of the fact that it is an identity; the ID column should be marked as db-generated (Auto Generated Value in the UI, or IsDbGenerated in the xml), and probably as the primary key. Then it will not attempt to insert it, and will update the value correctly after it is written.

    0 讨论(0)
  • 2020-12-03 09:04

    Check your ID property inside the Item class to ensure that it have attributes like this:

    [Column(Storage="_ID", AutoSync=AutoSync.OnInsert,
        DbType="INT NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
    

    Look at the IsDbGenerated=true, it is the important guy here.

    Maybe you created the DatabaseContext using the designer before adjusting the IDENTITY on the Sql Server, so just regenerate this class (by deleting the table in the designer and dropping it from the Server Explorer again).

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