Skip to main content

RETURNING SCOPE_IDENTITY() IN LINQ

Microsoft's Language Integrated Query is no doubt one of the most thrilling data access capability I cherish. This is just because of the flexibility you have in writing your queries within your code.

The power of LINQ is not limited to the data access as in (LINQ to SQL). LINQ can be used to query the active directory, XML, SharePoint lists etc.

Today I will like to discuss how to return @@IDENTITY or SCOPE_IDENTITY() in LINQ. The simple answer is to read the Id value you require immediately after submitting your changes.

e.g.

DataContext db = new ClassesDataContext();

PATIENT_DETAIL p = new PATIENT_DETAIL();

p.Address1 = txtAddress1.Text;
p.Address2 = txtAddress2.Text;
p.Address3 = txtAddress3.Text;
p.Address4 = txtAddress4.Text;

db.PATIENT_DETAILs.InsertOnSubmit(p);

db.SubmitChanges();

int myId = p.PASNumber; // This returns the Id generated by the database (where PASNumber represents the Primary key to be returned.)


QED

Comments

Anonymous said…
this is great. Do you have a VB example?

thanks!
Dim db As DataContext = New ClassesDataContext()

Dim p As New PATIENT_DETAIL()

p.Address1 = txtAddress1.Text
p.Address2 = txtAddress2.Text
p.Address3 = txtAddress3.Text
p.Address4 = txtAddress4.Text



db.PATIENT_DETAILs.InsertOnSubmit(p)

db.SubmitChanges()

Dim myId As Integer = p.PASNumber
Jahja.nl said…
How about when you insert multiple items (InserOnSubmit()), and at the end calling SubmitChanges().

How can I return the scope_identity() then?

J
dan rogy said…
My current project requires ability to display choice column value via color or image associated with a choice

But Sharepoint standard packaged misses that control

I am looking for available solutions on market

I came across

http://sharepointfields.com


Does anybody has experiece using it?

Popular posts from this blog

Get Sum of Columns in a SharePoint list (Threshold edition)

It is a known fact that once the treshold limit is reached in SP, everything seems frozen.  At this point you have some options. Increase the limit using powershell or from the Central Admin OR Index the columns that you will like to operate on and create views based on those. However programmatically if you want to sum a list that has reached its threshold.  You can do so in batches as hown below:          protected   void  GetSummary( out   long  ideas,  out   long  votes,  out   long  comments,  out   long  transform)         {              long  ideasum = 0;              long columntoSum = 0;              long  commentS...

Add Web Visual Studio templates to SharePoint Project

Would you like to add the web user control to SharePoint 2007 project development.  Then open the project file with notepad and add {349c5851-65df-11da-9384-00065b846f21} to the ProjectTypeGUIDs node.   The necessary change is shown below: < ProjectTypeGuids > {349c5851-65df-11da-9384-00065b846f21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} </ ProjectTypeGuids >