Link to home
Start Free TrialLog in
Avatar of whorsfall
whorsfallFlag for Australia

asked on

ADO.NET Entity Framework Add records efficiently.

Hi,

I have a simple routine to add records to a database using the entity framework. I wanted to make this
perform as fast as possible and wanted to make sure I am doing thing correctly.

To add multiple records to a table should I be creating a new instance of the record object each time.
PidTable pid_table = new PidTable(); so for 100 records a 100 object creations?

Also can I assume that the context.SaveChanges will buffer up all the changes in memory and
write them in one hit. So it is more efficient to have that at the end then within the loop
context.SaveChanges();

Also in regards to SaveChanges() I assume that the more records that are changed the more memory is used. Is there a limit to this is is it governed by the amount of free memory.

Additionally can I reclaim the memory back from SaveChanges() after the context is disposed or do I need to wait for .NET garbage collection.

Any advice greatly appreciated.

Ward.



private void fnAdd_100_Records()
        {
            
            CarDBEntities context = new CarDBEntities();
            
            decimal counter;

            for (counter = 1; counter <= 100; counter++)
            {
                PidTable pid_table = new PidTable();
                pid_table.ID = counter.ToString();
                pid_table.PID1 = (decimal)counter;
                context.AddToPidTable(pid_table);
            }

            context.SaveChanges();
            context.Dispose();

        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of whorsfall

ASKER

Hi,

Great help with your answers, thank you. So overall is I can assume I am doing this is the fastest way possible. Is my placement of the context.SaveChanges(); correct or should I put it within the loop for best performance.

Also u mentioned putting it in a using block is that not the same as using a .Dispose() method,
why is the using block better?

Thanks,

Ward
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Awsome great answers.

Thankyou.

Ward
Not a problem Ward, glad I was able to help.  ;=)