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.