Auto generate in LINQ to SQL

linq-to-sql

I have a table whit 2 columns , ID and name .I set 'YES' Identity for ID column .

I want to insert data to table whit LINQ .I want to get only name column from user in my application , and then ID column fill automatic to database and I can't give data that column and fill whitout I give it .

What should I do ?

I write in c# and work whit LINQ .

Best Answer

So your database field already is a INT IDENTITY - right?

Next, in your LINQ to SQL designer, you need to make sure your column is set to:

  • Auto Generated Value = TRUE
  • Auto-Sync = ON INSERT

enter image description here

Now if you add an entry to your database, the ID will be automatically updated from the value assigned to it by the database:

YourClass instance = new YourClass();
instance.Name = "some name";

YourDataContext.InsertOnSubmit(instance);
YourDataContext.SubmitChanges();

After the SubmitChanges call, your instance.ID should now contain the ID from the database.

Related Topic