Perform CRUD operations with EF Core

After EF Core is configured, you can use it to perform CRUD operations on your entity classes. Then, you can develop against C# classes, delegating the database operations to the context class. Database providers in turn translate it to database-specific query language. An example is SQL for a relational database. Queries are always executed against the database, even if the entities returned in the result already exist in the context.

Query data

The context object exposes a collection class for each entity type. In the preceding example, the context class exposes a collection of Pizza objects as Pizzas. Given that we have an instance of the context class, you can query the database for all pizzas:

C#Copy

var pizzas = await db.Pizzas.ToListAsync();

Insert data

You can use the same context object to insert a new pizza:

C#Copy

await db.pizzas.AddAsync(
    new Pizza { ID = 1, Name = "Pepperoni", Description = "The classic pepperoni pizza" });

Delete data

Delete operations are simple. They require only an ID of the item to be deleted:

C#Copy

var pizza = await db.pizzas.FindAsync(id);
if (pizza is null)
{
    //Handle error
}
db.pizzas.Remove(pizza);

Update data

Similarly, you can update an existing pizza:

C#Copy

int id = 1;
var updatepizza = new Pizza { Name = "Pineapple", Description = "Ummmm?" };
var pizza = await db.pizzas.FindAsync(id);
if (pizza is null)
{
    //Handle error
}
pizza.Description = updatepizza.Description;
pizza.Name = updatepizza.Name;
await db.SaveChangesAsync();
nutanix certification malaysia

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *