Tuesday, 22 March 2022

Entity Framework Core

 # Entity framework core

1. We create a class that derives from the DbContext class.
2. DbContext class is in Microsoft.EntityFrameworkCore namespace.
public class AppDbContext : DbContext
{ }
3. For the DbContext class to be able to do any useful work, it needs an instance of the DbContextOptions class.
4. The DbContextOptions instance carries configuration information such as the connection string, database provider to use etc.
5. To pass the DbContextOptions instance we use the constructor as shown in the example below.
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options)
        {
        }
    }
6. The DbContext class includes a DbSet<TEntity> property for each entity in the model.
7. The LINQ queries against the DbSet<TEntity> will be translated into queries against the underlying database.
8. To inject ef core service use
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<AppDbContext>(
            options => options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));

        services.AddMvc().AddXmlSerializerFormatters();
        services.AddTransient<IEmployeeRepository, MockEmployeeRepository>();
    }
9. UseSqlServer() extension method is used to configure our application specific DbContext class to use Microsoft SQL Server as the database.
10. To connect to a database, we need the database connection string which is provided as a parameter to UseSqlServer() extension method
{
  "ConnectionStrings": {
    "EmployeeDBConnection": "server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;Trusted_Connection=true"
  }
}

## Common entity framework core migration commands

1. Add-Migration     Adds a new migration
2. Update-Database     Updates the database to a specified migration

## Seed initial database data

1. In your application DbContext class, override OnModelCreating() method.

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public DbSet<Employee> Employees { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>().HasData(
            new Employee
            {
                Id = 1,
                Name = "Mark",
                Department = Dept.IT,
                Email = "mark@pragimtech.com"
            }
        );
    }
}

No comments:

Post a Comment

Search This Blog

Creating your first "Alexa" Skill

Index What is Alexa What is Alexa Skill? Why is it required when Alexa already equipped with voice assistant? Dev...