2

I am saving multiple objects to the database with a foreach loop. After these are saved i want to do something with the ID's of the saved objects.
This is my insert loop:

foreach (var Object in ListOfObjects)
{
    Object obj = new Object();
    obj.Objectvalue1 = Object.Value1;
    obj.Objectvalue2 = Object.Value2
    db.Objects.Add(obj);    
}
db.SaveChanges();

What i want to do is the following:

List<int> IDs = new List<int>();
foreach (var Object in ListOfObjects)
{
    Object obj = new Object();
    obj.Objectvalue1 = Object.Value1;
    obj.Objectvalue2 = Object.Value2
    db.Objects.Add(obj); 
    IDs.Add(obj.ID) //this should be the Primary key
}
db.SaveChanges();

The last example wont work because the ID will empty, You first want to save the data to the database for the Id to be filled, but I do not want to Save for every object i'm inserting.

I saw some Questions of getting the ID but those are all for inserting a single object, not multiple.

Summary: Is there a way to get a list or array of the id's of the inserted records.

3
  • Enumerate over your objects after you have saved them to get their ID's Commented Dec 2, 2015 at 18:41
  • @KiwiPiet wouldnt this give me all the objects id's from that table and not only the inserted objects? Commented Dec 2, 2015 at 18:53
  • Pretty sure you could just do an AddRange after you populate your List of objects and then after the SaveChanges you would have the list of IDs. Instead of iterating with an Add in a foreach. Commented Dec 2, 2015 at 19:29

1 Answer 1

4

You simply have to save the created objects that you add to the data base. So as you created to data object, add it to a list and then after you do the SaveChanges, each of those objects will have their ids and can be easily retrieved with

dataObjectList.Select((o) => o.ID).ToList();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.