Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get primary key value when i insert a new record?

Tags:

linq-to-sql

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.

like image 369
harshalb Avatar asked Apr 25 '09 06:04

harshalb


People also ask

How can I get auto increment value after insert?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.

Is it mandatory for the primary key to be given a value when a new record is inserted?

In practice, the primary key attribute is also marked as NOT NULL in most databases, meaning that attribute must always contain a value for the record to be inserted into the table.

How do I get the latest inserted record ID in SQL?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.


3 Answers

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

like image 97
eglasius Avatar answered Oct 04 '22 02:10

eglasius


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
    }
like image 24
aleemb Avatar answered Oct 04 '22 04:10

aleemb


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;
like image 34
Jose Basilio Avatar answered Oct 04 '22 03:10

Jose Basilio