locked
Get ID of newly inserted row with ADO.Net data services RRS feed

  • Question

  • How can I get the ID of newly inserted row in ADO.Net data services?

    Example:

    ctx.MergeOption = MergeOption.AppendOnly;
    contacts con = new contacts();
    con.LastName = "Lee";
    con.FirstName = "James"
    ctx.AddToContacts(con);
    ctx.SaveChanges();

    Note: ContactID is autogenerated from the database.


    I need to obtain:

    ContactID = ??


    Any ideas?

    Thanks,
    JFJ
    Friday, July 10, 2009 6:20 PM

Answers

  • Thanks a lot Matt, for your reply

    I was able to get the ID now.

    Below is my working code:

    ctx.MergeOption = MergeOption.AppendOnly;
    contacts con = new contacts();
    con.LastName = "Lee";
    con.FirstName = "James"
    ctx.AddToContacts(con);
    ctx.SaveChanges();
    int NewID = con.ContactID;


    • Marked as answer by jfj2009 Monday, July 13, 2009 6:40 PM
    Monday, July 13, 2009 6:39 PM

All replies

  • Hi,

    In general, if the server's response contains the ContactID value, then the 'contacts' object being tracked by the context should get updated with the server-generated value. I'm assuming that 'contacts' has a settable property of that name so that the value sent back can be stored.

    You can use a tool like Fiddler to check that the server's response contains the newly generated ContactID.

    I'm not 100% familiar with DataServiceContext.MergeOption, but you may need to set it to OverrideChanges or PreserveChanges to get the behavior described above.
    Matt Meehan, ADO.NET Data Services (Astoria)
    Saturday, July 11, 2009 6:20 AM
    Moderator
  • Thanks a lot Matt, for your reply

    I was able to get the ID now.

    Below is my working code:

    ctx.MergeOption = MergeOption.AppendOnly;
    contacts con = new contacts();
    con.LastName = "Lee";
    con.FirstName = "James"
    ctx.AddToContacts(con);
    ctx.SaveChanges();
    int NewID = con.ContactID;


    • Marked as answer by jfj2009 Monday, July 13, 2009 6:40 PM
    Monday, July 13, 2009 6:39 PM