tags:

views:

811

answers:

6

I am using LINQ-to-SQL class. It has a method object.InsertOnSubmit() .But it returns void so can i get primary key values after inserting a record.

I want the primary key value of recently inserted record.

A: 

If the model is set up properly, the PK should be set on the affected object (the one you just inserted) automagically.

HTH.

Seth

A: 

Are you calling SubmitChanges() on your data context after inserting the record? The changeset won't be evaluated until you do.

Dave L
A: 

Once you have called the InserOnSubmit(),primary key value is set to the corrosponding fiels in youe table object. You can simply access that property to get Primary Key.

Kapilg
+1  A: 

yes (Assuming it is an identity field).

Calling InsertOnSubmit alone doesn't send the insert to the db. You need to call SubmitChanges in order for any changes in the current datacontext instance to be sent to the db.

After you have called SubmitChanges, you can access the values from the instance you used when calling InsertOnSubmit. Linq to sql will populate those values for you when doing the insert (which occurs during SubmitChanges)

Check this example: http://msdn.microsoft.com/en-us/vbasic/bb737920.aspx#dynid

eglasius
+3  A: 

In short, you don't need to. The object itself is updated.

    public void Add(Person person)
    {
        using (MyEntities context = new MyEntities())
        {
            Context.Persons.InsertOnSaveChanges(person);
            Context.SaveChanges();
        }
    }

    public void Foo()
    {
        Person p = new Person { name = "John", age = 20 }
        Add(p);
        Int32 id = p.id;  // id contains the newly inserted object's id
    }
aleemb
+1  A: 

Here's an example of how that works:

var dc = new MyDataContext();
var cust = new Customer{FirstName="John", LastName="Smith"};
dc.Customer.InsertOnSubmit(cust);
dc.SubmitChanges();
//after SubmitChanges(), the Id is filled from the database
var customerPrimaryKey = cust.Id;
Jose Basilio