In this article, we will go through the process of using Entity Framework 7 (EF7) with a step by step source code scenario.
EF7 is an Object-Relational Mapping (ORM) framework for the .NET framework, which allows developers to interact with databases using C# or Visual Basic. It provides a simple and efficient way to work with databases by abstracting away the underlying database structure and providing a higher-level programming model.
In this guide, we will cover how to install the necessary packages, define a database context, create entities, and perform CRUD operations on the entities. We will also cover how to create and apply migration script to create the necessary database and tables. By the end of this guide, you will have a solid understanding of how to use EF7 in your .NET application.
- Install the necessary packages for EF7 by running the following command in the Package Manager Console:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
- Create a new class that will serve as the database context, and inherit from the DbContext class. In this example, the class is named MyDbContext.
public class MyDbContext : DbContext { public DbSet<MyEntity> MyEntities { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;"); } }
- Create a new class that represents an entity, in this example, MyEntity, that maps to a database table. Add the properties of the entity class that maps to the columns of the table.
public class MyEntity { public int Id { get; set; } public string Name { get; set; } }
- Using the MyDbContext class, you can now perform CRUD operations on the MyEntity table. Here's an example of how to insert a new record into the table:
using (var context = new MyDbContext()) { var myEntity = new MyEntity() { Name = "John Doe" }; context.MyEntities.Add(myEntity); context.SaveChanges(); }
In this example, we first create an instance of the MyDbContext class. Then, we create a new instance of the MyEntity class and set the properties of the entity. In this case, we are setting the Name property to "John Doe".
Next, we add the entity to the MyEntities DbSet using the Add method. The DbSet represents the table in the database where the entities will be stored.
Finally, we call the SaveChanges() method on the context to save the changes to the database. This method will insert the new entity into the table, and the new record will be persisted in the database.
It's worth noting that the Add method add the entity to the context memory and SaveChanges persist the state of the context into the database. Also, this example assumes that the database and tables are already created and the connection string is correctly set in the OnConfiguring method of the context class.
- To query the data from the table, you can use LINQ to query the DbSet property, MyEntities in this case. Here's an example of how to retrieve all records from the table:
using (var context = new MyDbContext()) { var myEntities = context.MyEntities.ToList(); }
- To update a record in the table, you can retrieve the record first, update the properties, and then call the SaveChanges() method on the context.
using (var context = new MyDbContext()) { var myEntity = context.MyEntities.FirstOrDefault(e => e.Id == 1); if (myEntity != null) { myEntity.Name = "Jane Doe"; context.SaveChanges(); } }
- To delete a record from the table, you can call the Remove method on the DbSet property, and then call the SaveChanges() method on the context.
using (var context = new MyDbContext()) { var myEntity = context.MyEntities.FirstOrDefault(e => e.Id == 1); if (myEntity != null) { context.MyEntities.Remove(myEntity); context.SaveChanges(); } }
This approach actually results in two SQL statements being executed: one to retrieve the entity from the database, and a second to delete it. A better approach is to delete the record without retreiving it from the database, here is a better practice:
using(var context = new MyDbContext()) { var myEntity = new MyEntity { Id = 1 }; context.MyEntities.Remove(myEntity); context.SaveChanges(); }
- Before you can use the EF7, you need to create the database and the table that corresponds to the entities you defined. You can use the command Add-Migration to create the migration script that will create the necessary database and tables.
Add-Migration InitialCreate
- Once the migration script is ready, you can apply it to the database by using the command Update-Database
Update-Database
- Once the database and tables are created, you can now start using the EF7 to interact with the database. You can use the context and entities you defined earlier to perform CRUD operations and querying the data.
Note that this is a simple example of how to use EF7 and should be adjusted to match your specific needs and requirements. EF7 offers a lot of flexibility and advanced features for working with databases, such as lazy loading, change tracking, and more.
Also, it's worth mentioning that this guide is based on the Code-First approach, where you define your entities first, and then the database and tables are created automatically, but there are other approaches such as Model-First and Database-First
I hope this guide helps you get started with using EF7 in your .NET application.