How to set the auto increment value=true in LINQ

Posted by Masuma85 under Regular Expressions on 1/14/2009 | Views : 9070 | Status : [Member] | Replies : 1
Hello all,
I have a table with names 'Employee' with four field EmployeeId,Name,Address,Age
I have set the EmployeeId is Primary key.I want that EmployeeId field will be incremented automatically whenever adding any new records.

Codebehind for insert is:
DataClassesDataContext db = new DataClassesDataContext();

Employee emp = new Employee {Name = "James", Address = "India", Age = 24};



[Column(Storage = "_EmployeeId", DbType = "Int NOT NULL", IsPrimaryKey = true,IsDbGenerated=true,CanBeNull=false)]

When I am running this application getting the following error:

Cannot insert the value NULL into column 'EmployeeId', table 'Habib.dbo.Employee'; column does not allow nulls. INSERT fails.
The statement has been terminated.

Any help is highly appreciated.



Posted by: Vuyiswamb on: 3/24/2009 [Member] [MVP] [Administrator] NotApplicable

It was pretty obvious that, as the identity column was and Int32, it was set to 0 as default, and when LINQ tried to insert that row in the table the SQL Server raised an error as this auto incremented field cannot be explicitly set. This is simply solved by using the IsDbGenerated attribute in the Column annotation description of the field, as shown in the following code.

private Int32 _id;

[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public Int32 Id { get { return this._id; } set { this._id = value; } }

This attribute tells LINQ not to give a value for this field as it is generated by the database at insert time.

Another very nice thing about this is that once you have inserted the object in the database, this field will hold the value generated by the database. Practically, this means that after executing the following code



the obj.Id property will contain the value that was assigned by the database.

Hope this helps.

Thank you for posting at .NETFUNDA, We are looking forward for your reply

Vuyiswa Maseko

Thank you for posting at Dotnetfunda

Masuma85, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response