0

I know this question has been asked like 100 times before because I've checked out most of them. None of them seem to work with EF6 though.

Simply, I want to use EF6 to write a record into a SQL Server database, and then recover the value of the Identity column after doing SaveChanges().

Here's my simple program:

        using (var ctx = new myEntities())
        {
            ctx.TinyUrl_Url.Add(new TinyUrl_Url()
            {
                UrlValue = tinyUrl
            });
            ctx.SaveChanges();
        }

The TinyUrl_Url table has 2 columns: UrlValue, and the Identity PK of UrlID. How can I get the value of UrlID after inserting the new row using EF6?

Thank you.

Barry Dysert
  • 665
  • 1
  • 9
  • 21
  • var addedUrl = ctx.TinyUrl_Url.Add(...); After SaveChanged the Id of object AddedUrl if filled with the Id that was given to the object that was inserted into the database – Harald Coppoolse Dec 11 '17 at 09:27

1 Answers1

0
int Id = ctx.UrlID;

Personally I do it this way-

context.Customers.Add(customer);
context.SaveChanges();//this generates the Id for customer
order.CustomerId = customer.Id;//finally I can set the Id

Should work after saving.

Arijit Mukherjee
  • 3,817
  • 2
  • 31
  • 51
  • I must be missing something because in trying to translate your code into mine, I still get a compile error. Here's what I have, trying to use your idea: using (var ctx = new myEntities()) { ctx.TinyUrl_Url.Add(new TinyUrl_Url() { UrlValue = tinyUrl }); ctx.SaveChanges(); long theID = TinyUrl_Url.Id; // no such property, Id Can you please tell me what I'm missing? – Barry Dysert Dec 11 '17 at 09:28
  • firstly create a new obj of TinyUrl and then add url to its property pass the object and then check @BarryDysert – Arijit Mukherjee Dec 12 '17 at 12:53