entity framework - insert new objects


When we want to insert data in to the data source, we must create an instance of an entity type and add the object to an object context. Before we can save a new object to the data source, we must first set all properties that do not support null values. The below code demonstrates how to insert new objects to a specific EntitySet - Customer.

using (var context = new SalesOrderManagementEntities())
Customer customer = new Customer { Name = "John", Address = "25,e-block" };
context.AddToCustomer(customer);
context.SaveChanges();
// Display customer details after adding a new customer
query = from c in context.Customer
		select c;
foreach (var c in query)
{
	Console.WriteLine(String.Format("{0} {1}",
		c.Name, c.Address));
}
Console.WriteLine();
Console.ReadLine();
}

In the above code, we have created a new customer object and set the Name and address properties.

The entity framework generates one AddToXXX method for every class generated in the entity data model. For the Customer class, it generates the AddToCustomer() method.

Note that we use InsertOnSubmit() method while using LINQ to SQL. Call the SaveChanges() method of the object context to insert the new customer to the database.