-->

Sunday, May 26, 2013

Insert Entities into database Table using Entity Framework 5: C# programming

Insert Entities into database Table using Entity Framework 5: C# programming

After creating databases with foreign key constraints in entity framework 5, its time to insert some records and save them for further references. In this article i will cover up, how to add entities and how entity framework processes these during saveChanges method. A database developer often use this method to insert records.


As i have added Student table which is a c# class in our solution, i will insert a record in the same table directly through code. I am using the same Winforms Application that we have used in previous article so make sure you have studied Creating databases in entity framework 5.

Note: "You must create an object of DataContext class in Form1's Constructor in order to insert some data in Student class."

To insert a record in database we will use the method i.e. EntityCollection<TEntity>.Add(). Lookout the c# programming code given below:

DataContext dc = new DataContext();
Student newStudent = new Student();
newStudent.Name = "Student 1";
newStudent.Age = 24;

dc.Student.Add(newStudent);
dc.SaveChanges();

All we are doing here is create a new instance of Student class and populate its properties. Then add that instance to Students set using EntityCollection<TEntity>.Add() method.

In above code Add() method is used to add newly created instance in database, and SaveChanges() method is used to save all the changes you have done with database.

Finally, go to your database and check, you will find the above instance there in Students table.

Download Source Code.

Update n Delete Entities in Entity Framework 5

Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved