Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I MANUALLY set an Identity field in LINQ-To-SQL (IDENTITY INSERT)

I have a table that normally, upon insert, the auto-key will increment. But, there are some instances when we want to set the ID (as would easily be done with "IDENTITY INSERT" in SQL).

Is there a way to accomplish this with LINQ to SQL?

Thanks,

like image 460
Timothy Khouri Avatar asked Feb 03 '09 15:02

Timothy Khouri


People also ask

Can I insert value for identity column in SQL?

To manually insert a new value into the Id column, we first must set the IDENTITY_INSERT flag ON as follows: SET IDENTITY_INSERT Students ON; To set the IDENTIT_INSERT flag ON we need to use the SET statement followed by the flag name and the name of the table.

How do I get the identity column value after insert?

After an INSERT, SELECT INTO, or bulk copy statement is completed, @@IDENTITY contains the last identity value that is generated by the statement. If the statement did not affect any tables with identity columns, @@IDENTITY returns NULL.


2 Answers

Take a look here: http://social.msdn.microsoft.com/Forums/en-US/linqtosql/thread/566e9540-911e-48b4-ac31-f69c0ab9f7fb/

Last reply here: http://forums.asp.net/t/1208607.aspx

like image 58
Eduardo Avatar answered Sep 30 '22 18:09

Eduardo


If you want to make IDENTITY increment always OFF

Edit the Model

public class TableName
{

    [Key,DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }

...
}
like image 21
Wowo Ot Avatar answered Sep 30 '22 19:09

Wowo Ot