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.
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.
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.
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.
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
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
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With