Reputation: 387
What's the best way to write a LINQ query that inserts a record and then returns the primary key of that newly inserted record using C# ?
Upvotes: 19
Views: 52537
Reputation: 3749
// Create a new Order object.
Order ord = new Order
{
OrderID = 12000,
ShipCity = "Seattle",
OrderDate = DateTime.Now
// …
};
// Add the new object to the Orders collection.
db.Orders.InsertOnSubmit(ord);
// Submit the change to the database.
try
{
db.SubmitChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
// Make some adjustments.
// ...
// Try again.
db.SubmitChanges();
}
return ord.OrderID;
Upvotes: 6
Reputation: 13024
Any field with AutoGeneratedValue=true will be filled in after that record is submitted to the database by dc.SubmitChanges()
Upvotes: 1
Reputation: 103605
The primary key value will be in that property after the SubmitChanges().
MyTable record = new MyTable();
record.Name = "James Curran";
db.MyTable.InsertOnSubmit(record);
db.SubmitChanges();
Console.WriteLine("record inserted as ID : {0}", record.Id);
Upvotes: 33