Skip to main content

Posts

Showing posts from 2008

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