Entity Framework - Add Single Entity


Follow the following steps to add new entity in DbContext, which inserts a new row in database table.

1. A new Employee entity object is created  and set EmployeeName to 'New Employee'.
2. We have created a new DBContext class object and added newEmployee entity object into Employees EntitySet.
3. Call SaveChanges method of DBContext which executes the generated insert query to the database.


class Program
{
    static void Main(string[] args)
    {
        //Employee entity object in disconnected scenario (out of the scope of DbContext)
        var newEmp = new Employee();

        //Employee name
        newEmp.EmployeeName = "New Employee";

        //create DBContext object
        using (var dbCtx = new EFSourceDBEntities())
        {
            //Add Student object into Employees DBset
            dbCtx.Employees.Add(newEmp);
                
            //SaveChanges method to save employee into database
            dbCtx.SaveChanges();
        }
    }
}

Alternatively, entity can also be added into DBContext.Entry by making it as Added state which results in the same insert query:

class Program
{
    static void Main(string[] args)
    {
         //Employee entity object in disconnected scenario (out of the scope of DbContext)
        var newEmp = new Employee();

        //Employee name
        newEmp.EmployeeName = "New Employee";

        //create DBContext object
        using (var dbCtx = new EFSourceDBEntities())
        {
            //Add newEmp entity into DbEntityEntry and mark EntityState as Added
            dbCtx.Entry(newEmp).State = System.Data.Entity.EntityState.Added;

            //SaveChanges method to save new Employee into database
            dbCtx.SaveChanges();
        }
    }
}
 

Praesent mattis

Pellentesque viverra vulputate enim. Aliquam erat volutpat. Pellentesque tristique ante ut risus. Quisque dictum. Integer nisl risus, sagittis convallis, rutrum id, elementum congue, nibh. Suspendisse dictum porta lectus. Donec placerat odio vel elit.

Read More