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.
            Asked
            
        
        
            Active
            
        
            Viewed 1.1e+01k times
        
    3 Answers
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
- 
                    2Maybe 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
- 
                    1how 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;
 
    
    
        Khalid Salameh
        
- 63
- 1
- 4
 
    