Entity Framework Core

Entity Framework (EF) Core is a lightweight, extensible, open-source and cross-platform version of the popular Entity Framework data access technology.

EF Core can serve as an object-relational mapper (O/RM), enabling .NET developers to work with a database using .NET objects, and eliminating the need for most of the data-access code they usually need to write.

With EF Core, data access is performed using a model. A model is made up of entity classes and a context object that represents a session with the database, allowing you to query and save data. You can generate a model from an existing database, hand code a model to match your database, or use EF Migrations to create a database from your model, and then evolve it as your model changes over time.

  • EF Core is an ORM (Object-Relational Mapper).
  • EF Core supports both the Code First approach and Database First approach
  • EF Core supports many relational and even non relational databases. EF Core is able to do this by using plug-in libraries called the database providers. These database providers are available as NuGet packages. 
  • One of the very important classes in Entity Framework Core is the DbContext class. This is the class that we use in our application code to interact with the underlying database. It is this class that manages the database connection and is used to retrieve and save data in the database.
  • Instances of your entity classes are retrieved from the database using Language Integrated Query (LINQ). 
  • Data is created, deleted, and modified in the database using instances of your entity classes. 

What is ORM?
ORM stands for Object-Relational Mapper and it enables developers to work with a database using business objects. Without an ORM like EF Core, we have to write a lot of custom data access code to store and retrieve data.


To configure we specify configuration in ConfigureServices() method in Startup.cs file.
public class Startup
{
    private IConfiguration _config;

    public Startup(IConfiguration config)
    {
        _config = config;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<AppDbContext>(
            options => options.UseSqlServer(_config.GetConnectionString("DBConnection")));

        services.AddMvc().AddXmlSerializerFormatters();
        services.AddTransient<IEmployeeRepository, MockEmployeeRepository>();
    }
}

    Difference between AddDbContext() and AddDbContextPool() methods
    • We can use either AddDbContext() or AddDbContextPool() method to register our application specific DbContext class with the ASP.NET Core dependency injection system.
    • The difference between AddDbContext() and AddDbContextPool() methods is, AddDbContextPool() method provides DbContext pooling.
    • With DbContext pooling, an instance from the DbContext pool is provided if available, rather than creating a new instance.
    • DbContext pooling is conceptually similar to how connection pooling works in ADO.NET.
    • From a performance standpoint AddDbContextPool() method is better over AddDbContext() method.

    Database Connection String in ASP.NET Core

    we can store the connection string in appsettings.json configuration file
    {
      "ConnectionStrings": {
        "EmployeeDBConnection""server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;Trusted_Connection=true"
      }
    }

    In classic asp.net we store application configuration in web.config file which is in XML format. In asp.net core, there are different configuration sources. One configuration source is appsettings.json file and it is in JSON format.

    To read connection string from appsettings.json file we use IConfiguration service GetConnectionString() method.


    What is the difference between the following in a database connection string
    • Trusted_Connection=True;
    • Integrated Security=SSPI;
    • Integrated Security=true;
    All the above 3 settings specify the same thing, use Integrated Windows Authentication to connect to SQL Server instead of using SQL Server authentication.


    What is the Repository Pattern?

    Repository Pattern is an abstraction of the Data Access Layer. It hides the details of how exactly the data is saved or retrieved from the underlying data source. The details of how the data is stored and retrieved are in the respective repository. 

    The interface in the repository pattern specifies
    • What operations (i.e methods) are supported by the repository
    • The data required for each of the operations i.e the parameters that need to be passed to the method and the data the method returns
    • The implementation details are in the respective repository class that implements the repository Interface

    public class Employee
    {
        public int Id { getset; }
        public string Name { getset; }
        public string Email { getset; }
    }
    public interface IEmployeeRepository
    {
        Employee GetEmployee(int Id);
        IEnumerable<Employee> GetAllEmployee();
        Employee Add(Employee employee);
        Employee Update(Employee employeeChanges);
    }


    IEmployeeRepository interface supports the following operations
    • Get all the employees
    • Get a single employee by id
    • Add a new employee
    • Update an employee
    The details of how these operations are implemented are in the repository class that implements this IEmployeeRepository interface 


    Benefits of Repository Pattern
    • The code is cleaner and easier to reuse and maintain.
    • Enables us to create loosely coupled systems. For example, if we want our application to work with oracle instead of SQL server, implement an OracleRepository that knows how to read and write to the Oracle database and register OracleRepository with the dependency injection system.
    • In a unit testing project, it is easy to replace a real repository with a fake implementation for testing.

    What is a migration in entity framework core 

    Migration is an entity framework core feature that keeps the database schema and our application model classes (also called entity class) in sync.

    We commonly use the following 3 common commands to work with migrations in entity framework core.

    CommandPurpose
    get-help about_entityframeworkcoreProvides entity framework core help
    Add-MigrationAdds a new migration
    Update-DatabaseUpdates the database to a specified migration




    Comments