Bad Dub Bad Dub - 23 days ago 14
C# Question

Adding the same entity object to SQL server database

Im trying to add the same object to a table using a for loop as a job entity may be required more than once. I tried it this way first but it only saves one record.

for (int i = 0; i < required; i++)
{
_Context.Jobs.AddObject(n);
}


Then I tried this way thinking entity framework might not see the objects as being different.

for (int i = 0; i < required; i++)
{
if (i > 0)
{
Job additionalJob = new Job();
additionalJob = n;
_salesContext.Jobs.AddObject(additionalJob);
}
else
{
_Context.Jobs.AddObject(n);
}
}


The database only saves on record. Any help on this would be greatly appreciated.

Answer

Classes are reference types. What ever n is you are setting the additionalJob to it, which is exactly the same thing. Classes use pointers to a space in memory so all you are doing is making two pointers. When you add the record EF is just adding the same data.

Instead of setting to n, copy the properties over from n.

ie,

additionaljob.Name = n.Name;

or

var additonalJob = new Job() { Name = n.Name };
Comments