WPF entity Framework return ID of added child record RRS feed

  • Question

  • Hi guys,

    Basically i am trying to return the ID of the added child record. My current code is....

     CounterfeitEntities db = new CounterfeitEntities();
                    int rowcount = Convert.ToInt32((flx_counterfeitParts[flx_counterfeitParts.SelectedIndex, 0]));
                    var countpart = db.CounterfeitParts.First(c => c.CounterfeitID == rowcount);
                    countpart.CounterfeitPartsImages.Add(new CounterfeitPartsImage
                        CountImageComment = txtCommentInput.Text,
                        CountImageURL = txtImageLinkInput.Text

    I have then tried various ways of getting the ID of the added child such as...

    string anything = countpart.ChildID
    string anything = countpart.CounterfeitPartsImage.ChildID

    Any help would be appreciated.


    Monday, November 19, 2012 3:45 PM


  • Entity framework will give you the ID after the SaveChanges is finished. If you bit reorganize your code, you would be get the ID almost effortless... I would declare the new CounterfeitPartsImage class outside from the Add method, and after SaveChanges you can get the ID of the saved object, of course if your data table have an ID field.


    CounterfeitPartsImage cpi = new CounterfeitPartsImage()
                        CountImageComment = txtCommentInput.Text,
                        CountImageURL = txtImageLinkInput.Text
    var cpiID = cpi.ID; //assuming that you have ID field

    Monday, November 19, 2012 6:58 PM