tags:

views:

145

answers:

3

How to retrieve identity ID when inserting a row in the db using linq?

A: 

LINQ to SQL should automatically retrieve the identity of the inserted object, and update the field you mapped to the primary key accordingly - so long as the mapped PK property is marked as [Column(IsDbGenerated=true)].

Pavel Minaev
+4  A: 
marc_s
gratz on the sql-server silver badge Marc
Remus Rusanu
Thanks, Remus! You're not far away from it yourself :-)
marc_s
A: 

I'm using the .net Entity Framework and I've came across the similar case. Following is the code sinppet:

public void SaveQuote(Domain.Quote currentQuote)
    {
        try
        {
            int newQuoteId;
            //Add quote and quoteline details to db 
            if (currentQuote != null)
            {
                using (QuoteContainer quoteContainer = new QuoteContainer())
                {
                    **quoteContainer.AddToQuote(currentQuote);**
                    **quoteContainer.SaveChanges();**

                    newQuoteId = currentQuote.QuoteId;
                }
            }
            else return;

            // Execution of some stored Procedure by using above newly generated QuoteId

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Can any one suggest whether the above approach is correct?

sandeept