LINQ to SQL operation and reading the identifier of the inserted record

Can someone explain to me how to insert into a Linq database with a transaction and read the identifier of this record?

+3
source share
2 answers

If you do not have a DBML setting, add it to your project.
To add DBML to your project from Solution Explorer:
Right click on your project -> go to Add new Item -> select LINQ to SQL Classes

To populate DBML with your tables, follow the link: View -> Server Explorer
Expand your database and drag your tables into the dbml viewer

Then, if your table is a caleld Widget:

DataClasses1DataContext db = new DataClasses1DataContext(myConnection);
db.Widgets.InsertOnSubmit(myWidget);

db.SubmitChanges();

//Here myWidget.Id will be set
+6
source

Just copy your changes to the database. A newly inserted object will have an identifier property automatically updated by the newly assigned identifier, and you can read it from there.

+3
source

Source: https://habr.com/ru/post/1783012/


All Articles