1

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.

Community
  • 1
  • 1
Djeroen
  • 571
  • 6
  • 21
  • Enumerate over your objects after you have saved them to get their ID's – KiwiPiet Dec 02 '15 at 18:41
  • @KiwiPiet wouldnt this give me all the objects id's from that table and not only the inserted objects? – Djeroen Dec 02 '15 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. – ewahner Dec 02 '15 at 19:29

1 Answers1

3

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();
SOHO Developer
  • 583
  • 4
  • 16