189

When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call? I am assuming this is pretty easy, I just don't know how.

Brian Webster
  • 30,033
  • 48
  • 152
  • 225
naspinski
  • 34,020
  • 36
  • 111
  • 167

3 Answers3

276

After you commit your object into the db the object receives a value in its ID field.

So:

myObject.Field1 = "value";

// Db is the datacontext
db.MyObjects.InsertOnSubmit(myObject);
db.SubmitChanges();

// You can retrieve the id from the object
int id = myObject.ID;
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Germstorm
  • 9,709
  • 14
  • 67
  • 83
  • 2
    Maybe you'll need to set your field to "database generated" and "update on insert" for this to work. – Sam Sep 22 '08 at 09:57
  • 1
    how do i do this in c# 4.0?? there is no insertonsubmit or submitchanges?? – Bat_Programmer Jul 04 '12 at 00:35
  • 1
    @Confused Programmer - it is the same, but with Context.Collection.Add() and SaveChanges() – naspinski Mar 19 '13 at 17:08
  • The behavior may be DB specific. When using SQLite this did not result in the ID being populated. – denver Mar 24 '19 at 03:16
  • I've used this before, but how to make this work on a multirelationship tables? Do I have to save the main tables first get the ID from both and then save both id to the relationship table? – CyberNinja Aug 12 '19 at 16:55
17

When inserting the generated ID is saved into the instance of the object being saved (see below):

protected void btnInsertProductCategory_Click(object sender, EventArgs e)
{
  ProductCategory productCategory = new ProductCategory();
  productCategory.Name = “Sample Category”;
  productCategory.ModifiedDate = DateTime.Now;
  productCategory.rowguid = Guid.NewGuid();
  int id = InsertProductCategory(productCategory);
  lblResult.Text = id.ToString();
}

//Insert a new product category and return the generated ID (identity value)
private int InsertProductCategory(ProductCategory productCategory)
{
  ctx.ProductCategories.InsertOnSubmit(productCategory);
  ctx.SubmitChanges();
  return productCategory.ProductCategoryID;
}

reference: http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4

Jason Stevenson
  • 4,004
  • 3
  • 29
  • 49
5

Try this:

MyContext Context = new MyContext(); 
Context.YourEntity.Add(obj);
Context.SaveChanges();
int ID = obj._ID;