Get Identity of all objects after SaveChanges

1k Views Asked by At

I am inserting objects at the same time using Entity framework like below.

context = new MyContext();
foreach (var x in lstX)
{ 
    var abc = new abc{ name= x.abcName };
    context.abcs.Add(abc);

    var xyz = new xyz{ name = x.xyzName };
    context.xyzs.Add(xyz);
}

context.SaveChanges();

Is it possible get the identity of all these inserted objects?

1

There are 1 best solutions below

0
On BEST ANSWER

When you call SaveChanges, the Identity field is populated on the original entity. So to obtain this id, simply store a reference to the identity and access it after SaveChanges:

context = new MyContext();
List<abc> addedABCs = new List<abc>();
List<xyz> addedXYZs = new List<xyz>();
foreach (var x in lstX)
{ 
    var abc = new abc{ name= x.abcName };
    addedABCs.Add(abc);
    context.abcs.Add(abc);

    var xyz = new xyz{ name = x.xyzName };
    addedXYZs.Add(xyz);
    context.xyzs.Add(xyz);
}

context.SaveChanges();

foreach (var abc in addedABCs) 
{
    Console.WriteLine("Added item with ID {0}", abc.Id);
}