views:

3986

answers:

2

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.

Thank you.

+19  A: 

After you commit your object into the db the object receives a value in it's 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;
Germstorm
So simple! This is why I love LINQ. Thank you.
naspinski
Maybe you'll need to set your field to "database generated" and "update on insert" for this to work.
Sam
Nope, worked exactly as shown above!
naspinski
+1  A: 

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