[Entity Framework] DbContext API – Adding/Updating/Deleting Entities

When you use EF,  what you are doing is just manipulating a collection with objects. When “SaveChanges()” is called, all the changes are converted into corresponding SQL statements, which were executed in the database.

 

1. Adding Entities

You can use the strongly typed “Add()” method of “DbSet” to add an entity to set.

  • public TEntity Add(TEntity entity)
using (var context = new ProductContext())
{
  Category food = context.Categories.Single(c => c.Name == "Food");
  Product p = new Product { Name = "Pizza", Description = "Junk Food", Price = 10.99M, Category = food };
  context.Products.Add(p);

  context.SaveChanges();

  Product pizza = context.Products.SingleOrDefault(x => x.Name == "Pizza");
  Console.WriteLine("{0}: {1}", pizza.Name, pizza.Price.ToString("c"));
}

 

2. Updating Entities

Updating an entity is very simple. You just need to modify the properties of an object and call “SaveChanges()”.

using (var context = new ProductContext())
{
  Product pizza = context.Products.SingleOrDefault(x => x.Name == "Pizza");

  pizza.Name = "Big Mac";
  pizza.Description = "Still Junk";
  pizza.Price = 6M;

  context.SaveChanges();

  Product bigMac = context.Products.SingleOrDefault(x => x.Name == "Big Mac");

  Console.WriteLine("{0}: {1}", bigMac.Name, bigMac.Price.ToString("c"));
}

 

3. Deleting Entities

The “Remove()” method of DbSet is used to delete an entity.

  • public TEntity Remove(TEntity entity)
using (var context = new ProductContext())
{
  Product bigMac = context.Products.SingleOrDefault(x => x.Name == "Big Mac");
  context.Products.Remove(bigMac);

  context.SaveChanges();

  bigMac = context.Products.SingleOrDefault(x => x.Name == "Big Mac");

  if (bigMac == null)
  {
    Console.WriteLine("Big Mac is removed from DB");
  }
  else
  {
    Console.WriteLine("What!!!");
  }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s