Ebircsa
Ebircsa

Reputation: 387

How to insert a record with LINQ and C# and return the Primary Key of that record

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

Answers (3)

kazem
kazem

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

GeekyMonkey
GeekyMonkey

Reputation: 13024

Any field with AutoGeneratedValue=true will be filled in after that record is submitted to the database by dc.SubmitChanges()

Upvotes: 1

James Curran
James Curran

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

Related Questions