When working in any application a common requirement is accessing the database.Writing the database access code could be tedious,as you need to take care of multiple things such as:
- Implementing logic for connecting to database
- Writing SQL queries for working with tables and columns
- Mapping the values in database to the classes in our application.
EF Core is an ORM library and so it provides the benefits when retrieving and storing data in the database.Some of the benefits of using EF Core are:
- Abstracting the underlying data access logic You don’t have to write low level SQL statements to work with the databases.
- Allows working with database columns and tables as objects in our application.This allows to work with the database using the same code which you use to write your application.
- Change Tracking
EF Core is cross platform and supports different databases such as
- SQL Server
- MySQL
- Postgre
- SQLite
- In-memory
Like .NET Core,EF Core is cross platform.You can work with any database for which there is a provider.It’s also faster than previous versions.
For using Entity Framework Core in your application,you define the Entity classes which are normal classes which represents the Entities and class deriving from the DbContext class.The class deriving from the DbContext class defines the DbSet<T> properties.
Following are some of the main steps for using Entity Framework in your application:
1.Install the EF Core NuGet packages.For example to install nuget for SQL Server:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
2.Decide development approach , Code-First or Database-First.Implement model classes,if you are using code first approach the you define your classes for which you want to generate the database.
- Code first approach EF Core creates the database and tables from the model classes.You use migration to achieve this.
- Database first approach EF Core creates the model classes from the database
3.Define Model classes,for example we are declaring a model class Employee:-
public class Employee { public int EmployeeId { get; set; } }
In the above example we have implemented property named EmployeeId,this is how EF Core uniquely identifies an object,this is the primary key.Any property having name ClassName+Id is the primary key.
3.Implement DbContext for the entities .For example you implement Employee DbContext as:
public partial class EmployeeDBContext : DbContext { public virtual DbSet<Employee> Employees{ get; set; } }
Once you define the DbContext you can add and save records using the context as:
context.Employees.Add(employee); context.SaveChanges();
EF Core supports various commands for creating or updating the database ,based on the model you can add migration as:
add-migration name
then you need to execute the appropriate database commands
update-database
Leave a Reply