.NET Core + ASP.NET Core Training Course Session 17
.NET Core What we learned? Session 6 ~ 16 Overview • ASP.NET Core Basics • Middleware, Controllers, Action Filters and Routing • Models • Views • Entity Framework Core (Modeling) • Entity Framework Core (Querying Data) • Entity Framework Core (Saving Data)
.NET Core What we’ll learn today? Session 16 Agenda • Entity Framework Core (Other Concepts) • DI • Migration
.NET Core Understanding EF Services Entity Framework Core Dependency Injection Entity Framework executes as a collection of services working together. A service is a reusable component. A service is typically an implementation of an interface. Services are available to other services via dependency injection (DI), which is implemented in EF using Microsoft.Extensions.DependencyInjection.
.NET Core Understanding EF Services, Terms Entity Framework Core Dependency Injection • Service A reusable component. In .NET, a service can be identified by a class or interface. By convention, Entity Framework only uses interfaces to identify services. • Service lifetime A description of the way in which a service is persisted and disposed across multiple uses of the same service type. • Service provider The mechanism for storing a collection of services. Also known as a service container. • Service collection The mechanism for constructing a service provider.
.NET Core Understanding EF Services, Categories of Services Entity Framework Core Dependency Injection • Context services Services that are related to a specific instance of DbContext. They provide functionality for working with the user model and context options. • Provider services Provider-specific implementations of services. For example, SQLite uses “provider services” to customize the behavior of SQL generation, migrations, and file I/O. • Design-time services Services used when a developer is creating an application. For example, EF commands uses design-time services to execute migrations and code generation (aka scaffolding).
.NET Core Understanding EF Services, Categories of Services Entity Framework Core Dependency Injection • User services A user can define custom services to interact with EF. These are written in application code, not provider code. For example, users can provide an implementation of IModelCustomizer for controlling how a model is created.
.NET Core Understanding EF Services, Service Lifetime Entity Framework Core Dependency Injection • Transient Transient lifetime services are created each time they are injected into other services. This isolates each instance of the service. For example, MigrationsScaffolder should not be reused, therefore it is registered as transient. • Scoped Scoped lifetime services are created once per DbContext instance. This is used to isolate instance of DbContext. For example, StateManager is added as scoped because it should only track entity states for one context.
.NET Core Understanding EF Services, Service Lifetime Entity Framework Core Dependency Injection • Singleton Singleton lifetime services exists once per service provider and span all scopes. Each time the service is injected, the same instance is used. For example, IModelCustomizer is a singleton because it is idempotent, meaning each call to IModelCustomizer.Customize() does not change the customizer.
.NET Core How AddDbContext works Entity Framework Core Dependency Injection EF provides an extension method AddDbContext<TContext>() for adding using EF into a service collection. This method adds the following into a service collection: • TContext as “scoped” • DbContextOptions as a “singleton” • DbContextOptionsFactory<T> as a “singleton” AddDbContext does not add any context services, provider services, or design-time services to the service collection (except for special cases). DbContext constructs its own internal service provider for this.
.NET Core How AddDbContext works - Special cases Entity Framework Core Dependency Injection AddDbContext adds DbContextOptionsFactory<T> to the service collection AddDbContext was called on (which is used to create the “external” service provider). DbContextOptionsFactory<T> acts as a bridge between the external service provider and DbContext’s internal service provider. If the external provider has services for ILoggerFactory or IMemoryCache, these will be added to the internal service provider. The bridging is done for these common scenarios so users can easily configure logging and memory caching without needing to provide a custom internal service provider.
.NET Core DbContext’s internal service provider Entity Framework Core Dependency Injection By default, DbContext uses an internal service provider that is separate from all other service providers in the application. This internal provider is constructed from an instance of DbContextOptions. Methods such as UseSqlServer() extend the construction step add specialized services for their database system.
.NET Core Providing a custom internal service provider Entity Framework Core Dependency Injection DbContextOptionsBuilder provides an API for giving a custom service provider to DbContext for EF to use internally. This API is DbContextOptions.UseInternalServiceProvider(IServiceProvider provider). If a custom service provider is provided, DbContext will not use DbContextOptions to create its own internal service provider. The custom service provider must already have provider-specific services added. Database provider writers should provided methods such as AddEntityFrameworkSqlServer” or “AddEntityFrameworkSqlite” to simplify the process of creating a custom service container.
.NET Core Providing a custom internal service provider Entity Framework Core Dependency Injection
.NET Core Service provider caching Entity Framework Core Dependency Injection EF caches this internal service provider with IDbContextOptions as the key. This means the service provider is only created once per unique set of options. It is reused when a DbContext is instantiated using a set of options that have already been used during the application lifetime.
.NET Core Required Provider Services Entity Framework Core Dependency Injection EF database providers must register a basic set of services. These required services are defined as properties on IDatabaseProviderServices. Provider writers may need to implement some services from scratch. Others have partial or complete implementations in EF’s library that can be reused.
.NET Core Package Manager Console (Visual Studio) Entity Framework Core Package Manager Console Installation Package Manager Console commands are installed with the Microsoft.EntityFrameworkCore.Tools package. Install-Package Microsoft.EntityFrameworkCore.Tools -Pre
.NET Core Package Manager Console (Visual Studio) Entity Framework Core Package Manager Console Installation Package Manager Console commands are installed with the Microsoft.EntityFrameworkCore.Tools package. Install-Package Microsoft.EntityFrameworkCore.Tools –Pre On .NET Core and ASP.NET Core projects, add -Verbose to any Package Manager Console command to see the equivalent .NET Core CLI command that was invoked.
.NET Core Package Manager Console (Visual Studio) Entity Framework Core Package Manager Console All commands support the common parameters: -Verbose -Debug -ErrorAction -ErrorVariable -WarningAction -WarningVariable -OutBuffer -PipelineVariable -OutVariable
.NET Core Add-Migration Entity Framework Core Package Manager Console SYNTAX Add-Migration [-Name] <String> [-OutputDir <String>] [-Context <String>] [- Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>] PARAMETERS -Name <String> Specifies the name of the migration.
.NET Core Add-Migration Entity Framework Core Package Manager Console -OutputDir <String> The directory (and sub-namespace) to use. If omitted, "Migrations" is used. Relative paths are relative to project directory. -Context <String> Specifies the DbContext to use. If omitted, the default DbContext is used. -Project <String> Specifies the project to use. If omitted, the default project is used.
.NET Core Add-Migration Entity Framework Core Package Manager Console -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used.
.NET Core Remove-Migration Entity Framework Core Package Manager Console Removes the last migration. SYNTAX Remove-Migration [-Context <String>] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [-Force] [<CommonParameters>]
.NET Core Remove-Migration Entity Framework Core Package Manager Console PARAMETERS -Context <String> Specifies the DbContext to use. If omitted, the default DbContext is used. -Project <String> Specifies the project to use. If omitted, the default project is used. -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used.
.NET Core Remove-Migration Entity Framework Core Package Manager Console -Environment <String> Specifies the environment to use. If omitted, "Development" is used. -Force [<SwitchParameter>] Removes the last migration without checking the database. If the last migration has been applied to the database, you will need to manually reverse the changes it made.
.NET Core Scaffold-DbContext Entity Framework Core Package Manager Console Scaffolds a DbContext and entity type classes for a specified database. SYNTAX Scaffold-DbContext [-Connection] <String> [-Provider] <String> [-OutputDir <String>] [-Context <String>] [-Schemas <String>] [-Tables <String>] [-DataAnnotations] [-Force] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>]
.NET Core Scaffold-DbContext Entity Framework Core Package Manager Console PARAMETERS -Connection <String> Specifies the connection string of the database. -Provider <String> Specifies the provider to use. For example, Microsoft.EntityFrameworkCore.SqlServer. -OutputDir <String> Specifies the directory to use to output the classes. If omitted, the top-level project directory is used.
.NET Core Scaffold-DbContext Entity Framework Core Package Manager Console -Context <String> Specifies the name of the generated DbContext class. -Schemas <String> Specifies the schemas for which to generate classes. -Tables <String> Specifies the tables for which to generate classes.
.NET Core Scaffold-DbContext Entity Framework Core Package Manager Console -DataAnnotations [<SwitchParameter>] Use DataAnnotation attributes to configure the model where possible. If omitted, the output code will use only the fluent API. -Force [<SwitchParameter>] Force scaffolding to overwrite existing files. Otherwise, the code will only proceed if no output files would be overwritten. -Project <String> Specifies the project to use. If omitted, the default project is used.
.NET Core Scaffold-DbContext Entity Framework Core Package Manager Console -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used.
.NET Core Script-Migration Entity Framework Core Package Manager Console Generates a SQL script from migrations. SYNTAX Script-Migration -From <String> -To <String> [-Idempotent] [-Context <String>] [- Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>] Script-Migration [-From <String>] [-Idempotent] [-Context <String>] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>]
.NET Core Script-Migration Entity Framework Core Package Manager Console PARAMETERS -From <String> Specifies the starting migration. If omitted, '0' (the initial database) is used. -To <String> Specifies the ending migration. If omitted, the last migration is used. -Idempotent [<SwitchParameter>] Generates an idempotent script that can be used on a database at any migration.
.NET Core Script-Migration Entity Framework Core Package Manager Console -Context <String> Specifies the DbContext to use. If omitted, the default DbContext is used. -Project <String> Specifies the project to use. If omitted, the default project is used. -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used.
.NET Core Update-Database Entity Framework Core Package Manager Console Updates the database to a specified migration. SYNTAX Update-Database [[-Migration] <String>] [-Context <String>] [-Project <String>] [- StartupProject <String>] [-Environment <String>] [<CommonParameters>]
.NET Core Update-Database Entity Framework Core Package Manager Console PARAMETERS -Migration <String> Specifies the target migration. If '0', all migrations will be reverted. If omitted, all pending migrations will be applied. -Context <String> Specifies the DbContext to use. If omitted, the default DbContext is used. -Project <String> Specifies the project to use. If omitted, the default project is used.
.NET Core Use-DbContext Entity Framework Core Package Manager Console Sets the default DbContext to use. SYNTAX Use-DbContext [-Context] <String> [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>]
.NET Core Use-DbContext Entity Framework Core Package Manager Console PARAMETERS -Context <String> Specifies the DbContext to use. -Project <String> Specifies the project to use. If omitted, the default project is used. -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used.
.NET Core Using EF Core commands and EF 6 commands side-by-side Entity Framework Core Package Manager Console EF Core commands do not work on EF 6 or earlier version of EF. However, EF Core re- uses some of the same command names from these earlier versions. These commands can be installed side-by-side, however, EF does not automatically know which version of the command to use. This is solved by prefixing the command with the module name. The EF 6 commands PowerShell module is named “EntityFramework”, and the EF Core module is named “EntityFrameworkCore”. Without the prefix, PowerShell may call the wrong version of the command.
.NET Core Using EF Core commands and EF 6 commands side-by-side Entity Framework Core Package Manager Console
.NET Core Common Errors - Error: “No parameterless constructor was found” Entity Framework Core Package Manager Console Design-time tools attempt to automatically find how your application creates instances of your DbContext type. If EF cannot find a suitable way to initialize your DbContext, you may encounter this error. No parameterless constructor was found on 'TContext'. Either add a parameterless constructor to 'TContext' or add an implementation of 'IDbContextFactory<TContext>' in the same assembly as 'TContext'. As the error message suggests, one solution is to add an implementation of IDbContextFactory<TContext> to the current project. See Using IDbContextFactory<TContext> for an example of how to create this factory.
.NET Core .NET Core CLI Entity Framework Core .NET Core CLI Installation Prerequisites EF command-line tools requires .NET Core CLI Preview 2 or newer. Supported Frameworks • .NET Framework 4.5.1 and newer. (“net451”, “net452”, “net46”, etc.) • .NET Core App 1.0. (“netcoreapp1.0”)
.NET Core .NET Core CLI Entity Framework Core .NET Core CLI Install by editing project.json EF command-line tools for .NET Core CLI are installed by manually editing project.json. 1. Add Microsoft.EntityFrameworkCore.Tools as a “tool” and Microsoft.EntityFrameworkCore.Design as a build-only dependency under “dependencies”. See sample project.json below. 2. Execute dotnet restore. If restore does not succeed, the command-line tools may not have installed correctly. The resulting project.json should include these items (in addition to your other project dependencies).
.NET Core .NET Core CLI Entity Framework Core .NET Core CLI
.NET Core .NET Core CLI Entity Framework Core .NET Core CLI A build-only dependency ("type": "build") means this dependency is local to the current project. For example, if Project A has a build only dependency and Project B depends on A, dotnet restore will not add A’s build-only dependencies into Project B.
.NET Core .NET Core CLI - Usage Entity Framework Core .NET Core CLI Commands can be run from the command line by navigating to the project directory and executing dotnet ef [subcommand]. To see usage, add --help to any command to see more information about parameters and subcommands.
.NET Core .NET Core CLI - dotnet-ef Entity Framework Core .NET Core CLI Usage: dotnet ef [options] [command] Options: -h|--help Show help information -p|--project <PROJECT> The project to target (defaults to the project in the current directory). Can be a path to a project.json or a project directory. -s|--startup-project <PROJECT> The path to the project containing Startup (defaults to the target project). Can be a path to a project.json or a project directory.
.NET Core .NET Core CLI - dotnet-ef Entity Framework Core .NET Core CLI -c|--configuration <CONFIGURATION> Configuration under which to load (defaults to Debug) -f|--framework <FRAMEWORK> Target framework to load from the startup project (defaults to the framework most compatible with .NETCoreApp,Version=v1.0). -b|--build-base-path <OUTPUT_DIR> Directory in which to find temporary outputs. -o|--output <OUTPUT_DIR> Directory in which to find outputs
.NET Core .NET Core CLI - dotnet-ef Entity Framework Core .NET Core CLI Commands: • database Commands to manage your database • dbcontext Commands to manage your DbContext types • migrations Commands to manage your migrations
.NET Core .NET Core CLI - dotnet-ef-database Entity Framework Core .NET Core CLI Usage: dotnet ef database [options] [command] Options: -h|--help Show help information -v|--verbose Enable verbose output Commands: drop Drop the database for specific environment update Updates the database to a specified migration
.NET Core .NET Core CLI - dotnet-ef-database-drop Entity Framework Core .NET Core CLI Usage: dotnet ef database drop [options] Options: -e|--environment <environment> The environment to use. If omitted, "Development" is used. -c|--context <context> The DbContext to use. If omitted, the default DbContext is used -f|--force Drop without confirmation -h|--help Show help information -v|--verbose Enable verbose output
.NET Core .NET Core CLI - dotnet-ef-database-update Entity Framework Core .NET Core CLI Usage: dotnet ef database update [arguments] [options] Arguments: [migration] The target migration. If '0', all migrations will be reverted. If omitted, all pending migrations will be applied
.NET Core .NET Core CLI - dotnet-ef-dbcontext Entity Framework Core .NET Core CLI Usage: dotnet ef dbcontext [options] [command] Options: -h|--help Show help information -v|--verbose Enable verbose output Commands: list List your DbContext types scaffold Scaffolds a DbContext and entity type classes for a specified database
.NET Core .NET Core CLI - dotnet-ef-dbcontext-list Entity Framework Core .NET Core CLI Usage: dotnet ef dbcontext list [options] Options: -e|--environment <environment> The environment to use. If omitted, "Development" is used. --json Use json output. JSON is wrapped by '//BEGIN' and '//END' -h|--help Show help information -v|--verbose Enable verbose output
.NET Core .NET Core CLI - dotnet-ef-dbcontext-scaffold Entity Framework Core .NET Core CLI Usage: dotnet ef dbcontext scaffold [arguments] [options] Arguments: [connection] The connection string of the database [provider] The provider to use. For example, Microsoft.EntityFrameworkCore.SqlServer
.NET Core .NET Core CLI - dotnet-ef-dbcontext-scaffold Entity Framework Core .NET Core CLI Options: -a|--data-annotations Use DataAnnotation attributes to configure the model where possible. If omitted, the output code will use only the fluent API. -c|--context <name> Name of the generated DbContext class. -f|--force Force scaffolding to overwrite existing files. Otherwise, the code will only proceed if no output files would be overwritten. -o|--output-dir <path> Directory of the project where the classes should be output. If omitted, the top-level project directory is used.
.NET Core .NET Core CLI - dotnet-ef-dbcontext-scaffold Entity Framework Core .NET Core CLI --schema <schema> Selects a schema for which to generate classes. -t|--table <schema.table> Selects a table for which to generate classes. -e|--environment <environment> The environment to use. If omitted, "Development" is used. -h|--help Show help information -v|--verbose Enable verbose output
.NET Core .NET Core CLI - dotnet-ef-migrations Entity Framework Core .NET Core CLI Usage: dotnet ef migrations [options] [command] Options: -h|--help Show help information -v|--verbose Enable verbose output Commands: add Add a new migration list List the migrations remove Remove the last migration script Generate a SQL script from migrations
.NET Core .NET Core CLI - dotnet-ef-migrations-add Entity Framework Core .NET Core CLI Usage: dotnet ef migrations add [arguments] [options] Arguments: [name] The name of the migration
.NET Core .NET Core CLI - dotnet-ef-migrations-add Entity Framework Core .NET Core CLI Options: -o|--output-dir <path> The directory (and sub-namespace) to use. If omitted, "Migrations" is used. Relative paths are relative the directory in which the command is executed. -c|--context <context> The DbContext to use. If omitted, the default DbContext is used -e|--environment <environment> The environment to use. If omitted, "Development" is used. --json Use json output. JSON is wrapped by '//BEGIN' and '//END' -h|--help Show help information -v|--verbose Enable verbose output
.NET Core .NET Core CLI - dotnet-ef-migrations-add Entity Framework Core .NET Core CLI Options: -o|--output-dir <path> The directory (and sub-namespace) to use. If omitted, "Migrations" is used. Relative paths are relative the directory in which the command is executed. -c|--context <context> The DbContext to use. If omitted, the default DbContext is used -e|--environment <environment> The environment to use. If omitted, "Development" is used. --json Use json output. JSON is wrapped by '//BEGIN' and '//END' -h|--help Show help information -v|--verbose Enable verbose output
.NET Core Demo Demo

.NET Core, ASP.NET Core Course, Session 17

  • 1.
    .NET Core +ASP.NET Core Training Course Session 17
  • 2.
    .NET Core What welearned? Session 6 ~ 16 Overview • ASP.NET Core Basics • Middleware, Controllers, Action Filters and Routing • Models • Views • Entity Framework Core (Modeling) • Entity Framework Core (Querying Data) • Entity Framework Core (Saving Data)
  • 3.
    .NET Core What we’lllearn today? Session 16 Agenda • Entity Framework Core (Other Concepts) • DI • Migration
  • 4.
    .NET Core Understanding EFServices Entity Framework Core Dependency Injection Entity Framework executes as a collection of services working together. A service is a reusable component. A service is typically an implementation of an interface. Services are available to other services via dependency injection (DI), which is implemented in EF using Microsoft.Extensions.DependencyInjection.
  • 5.
    .NET Core Understanding EFServices, Terms Entity Framework Core Dependency Injection • Service A reusable component. In .NET, a service can be identified by a class or interface. By convention, Entity Framework only uses interfaces to identify services. • Service lifetime A description of the way in which a service is persisted and disposed across multiple uses of the same service type. • Service provider The mechanism for storing a collection of services. Also known as a service container. • Service collection The mechanism for constructing a service provider.
  • 6.
    .NET Core Understanding EFServices, Categories of Services Entity Framework Core Dependency Injection • Context services Services that are related to a specific instance of DbContext. They provide functionality for working with the user model and context options. • Provider services Provider-specific implementations of services. For example, SQLite uses “provider services” to customize the behavior of SQL generation, migrations, and file I/O. • Design-time services Services used when a developer is creating an application. For example, EF commands uses design-time services to execute migrations and code generation (aka scaffolding).
  • 7.
    .NET Core Understanding EFServices, Categories of Services Entity Framework Core Dependency Injection • User services A user can define custom services to interact with EF. These are written in application code, not provider code. For example, users can provide an implementation of IModelCustomizer for controlling how a model is created.
  • 8.
    .NET Core Understanding EFServices, Service Lifetime Entity Framework Core Dependency Injection • Transient Transient lifetime services are created each time they are injected into other services. This isolates each instance of the service. For example, MigrationsScaffolder should not be reused, therefore it is registered as transient. • Scoped Scoped lifetime services are created once per DbContext instance. This is used to isolate instance of DbContext. For example, StateManager is added as scoped because it should only track entity states for one context.
  • 9.
    .NET Core Understanding EFServices, Service Lifetime Entity Framework Core Dependency Injection • Singleton Singleton lifetime services exists once per service provider and span all scopes. Each time the service is injected, the same instance is used. For example, IModelCustomizer is a singleton because it is idempotent, meaning each call to IModelCustomizer.Customize() does not change the customizer.
  • 10.
    .NET Core How AddDbContextworks Entity Framework Core Dependency Injection EF provides an extension method AddDbContext<TContext>() for adding using EF into a service collection. This method adds the following into a service collection: • TContext as “scoped” • DbContextOptions as a “singleton” • DbContextOptionsFactory<T> as a “singleton” AddDbContext does not add any context services, provider services, or design-time services to the service collection (except for special cases). DbContext constructs its own internal service provider for this.
  • 11.
    .NET Core How AddDbContextworks - Special cases Entity Framework Core Dependency Injection AddDbContext adds DbContextOptionsFactory<T> to the service collection AddDbContext was called on (which is used to create the “external” service provider). DbContextOptionsFactory<T> acts as a bridge between the external service provider and DbContext’s internal service provider. If the external provider has services for ILoggerFactory or IMemoryCache, these will be added to the internal service provider. The bridging is done for these common scenarios so users can easily configure logging and memory caching without needing to provide a custom internal service provider.
  • 12.
    .NET Core DbContext’s internalservice provider Entity Framework Core Dependency Injection By default, DbContext uses an internal service provider that is separate from all other service providers in the application. This internal provider is constructed from an instance of DbContextOptions. Methods such as UseSqlServer() extend the construction step add specialized services for their database system.
  • 13.
    .NET Core Providing acustom internal service provider Entity Framework Core Dependency Injection DbContextOptionsBuilder provides an API for giving a custom service provider to DbContext for EF to use internally. This API is DbContextOptions.UseInternalServiceProvider(IServiceProvider provider). If a custom service provider is provided, DbContext will not use DbContextOptions to create its own internal service provider. The custom service provider must already have provider-specific services added. Database provider writers should provided methods such as AddEntityFrameworkSqlServer” or “AddEntityFrameworkSqlite” to simplify the process of creating a custom service container.
  • 14.
    .NET Core Providing acustom internal service provider Entity Framework Core Dependency Injection
  • 15.
    .NET Core Service providercaching Entity Framework Core Dependency Injection EF caches this internal service provider with IDbContextOptions as the key. This means the service provider is only created once per unique set of options. It is reused when a DbContext is instantiated using a set of options that have already been used during the application lifetime.
  • 16.
    .NET Core Required ProviderServices Entity Framework Core Dependency Injection EF database providers must register a basic set of services. These required services are defined as properties on IDatabaseProviderServices. Provider writers may need to implement some services from scratch. Others have partial or complete implementations in EF’s library that can be reused.
  • 17.
    .NET Core Package ManagerConsole (Visual Studio) Entity Framework Core Package Manager Console Installation Package Manager Console commands are installed with the Microsoft.EntityFrameworkCore.Tools package. Install-Package Microsoft.EntityFrameworkCore.Tools -Pre
  • 18.
    .NET Core Package ManagerConsole (Visual Studio) Entity Framework Core Package Manager Console Installation Package Manager Console commands are installed with the Microsoft.EntityFrameworkCore.Tools package. Install-Package Microsoft.EntityFrameworkCore.Tools –Pre On .NET Core and ASP.NET Core projects, add -Verbose to any Package Manager Console command to see the equivalent .NET Core CLI command that was invoked.
  • 19.
    .NET Core Package ManagerConsole (Visual Studio) Entity Framework Core Package Manager Console All commands support the common parameters: -Verbose -Debug -ErrorAction -ErrorVariable -WarningAction -WarningVariable -OutBuffer -PipelineVariable -OutVariable
  • 20.
    .NET Core Add-Migration Entity FrameworkCore Package Manager Console SYNTAX Add-Migration [-Name] <String> [-OutputDir <String>] [-Context <String>] [- Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>] PARAMETERS -Name <String> Specifies the name of the migration.
  • 21.
    .NET Core Add-Migration Entity FrameworkCore Package Manager Console -OutputDir <String> The directory (and sub-namespace) to use. If omitted, "Migrations" is used. Relative paths are relative to project directory. -Context <String> Specifies the DbContext to use. If omitted, the default DbContext is used. -Project <String> Specifies the project to use. If omitted, the default project is used.
  • 22.
    .NET Core Add-Migration Entity FrameworkCore Package Manager Console -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used.
  • 23.
    .NET Core Remove-Migration Entity FrameworkCore Package Manager Console Removes the last migration. SYNTAX Remove-Migration [-Context <String>] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [-Force] [<CommonParameters>]
  • 24.
    .NET Core Remove-Migration Entity FrameworkCore Package Manager Console PARAMETERS -Context <String> Specifies the DbContext to use. If omitted, the default DbContext is used. -Project <String> Specifies the project to use. If omitted, the default project is used. -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used.
  • 25.
    .NET Core Remove-Migration Entity FrameworkCore Package Manager Console -Environment <String> Specifies the environment to use. If omitted, "Development" is used. -Force [<SwitchParameter>] Removes the last migration without checking the database. If the last migration has been applied to the database, you will need to manually reverse the changes it made.
  • 26.
    .NET Core Scaffold-DbContext Entity FrameworkCore Package Manager Console Scaffolds a DbContext and entity type classes for a specified database. SYNTAX Scaffold-DbContext [-Connection] <String> [-Provider] <String> [-OutputDir <String>] [-Context <String>] [-Schemas <String>] [-Tables <String>] [-DataAnnotations] [-Force] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>]
  • 27.
    .NET Core Scaffold-DbContext Entity FrameworkCore Package Manager Console PARAMETERS -Connection <String> Specifies the connection string of the database. -Provider <String> Specifies the provider to use. For example, Microsoft.EntityFrameworkCore.SqlServer. -OutputDir <String> Specifies the directory to use to output the classes. If omitted, the top-level project directory is used.
  • 28.
    .NET Core Scaffold-DbContext Entity FrameworkCore Package Manager Console -Context <String> Specifies the name of the generated DbContext class. -Schemas <String> Specifies the schemas for which to generate classes. -Tables <String> Specifies the tables for which to generate classes.
  • 29.
    .NET Core Scaffold-DbContext Entity FrameworkCore Package Manager Console -DataAnnotations [<SwitchParameter>] Use DataAnnotation attributes to configure the model where possible. If omitted, the output code will use only the fluent API. -Force [<SwitchParameter>] Force scaffolding to overwrite existing files. Otherwise, the code will only proceed if no output files would be overwritten. -Project <String> Specifies the project to use. If omitted, the default project is used.
  • 30.
    .NET Core Scaffold-DbContext Entity FrameworkCore Package Manager Console -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used.
  • 31.
    .NET Core Script-Migration Entity FrameworkCore Package Manager Console Generates a SQL script from migrations. SYNTAX Script-Migration -From <String> -To <String> [-Idempotent] [-Context <String>] [- Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>] Script-Migration [-From <String>] [-Idempotent] [-Context <String>] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>]
  • 32.
    .NET Core Script-Migration Entity FrameworkCore Package Manager Console PARAMETERS -From <String> Specifies the starting migration. If omitted, '0' (the initial database) is used. -To <String> Specifies the ending migration. If omitted, the last migration is used. -Idempotent [<SwitchParameter>] Generates an idempotent script that can be used on a database at any migration.
  • 33.
    .NET Core Script-Migration Entity FrameworkCore Package Manager Console -Context <String> Specifies the DbContext to use. If omitted, the default DbContext is used. -Project <String> Specifies the project to use. If omitted, the default project is used. -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used.
  • 34.
    .NET Core Update-Database Entity FrameworkCore Package Manager Console Updates the database to a specified migration. SYNTAX Update-Database [[-Migration] <String>] [-Context <String>] [-Project <String>] [- StartupProject <String>] [-Environment <String>] [<CommonParameters>]
  • 35.
    .NET Core Update-Database Entity FrameworkCore Package Manager Console PARAMETERS -Migration <String> Specifies the target migration. If '0', all migrations will be reverted. If omitted, all pending migrations will be applied. -Context <String> Specifies the DbContext to use. If omitted, the default DbContext is used. -Project <String> Specifies the project to use. If omitted, the default project is used.
  • 36.
    .NET Core Use-DbContext Entity FrameworkCore Package Manager Console Sets the default DbContext to use. SYNTAX Use-DbContext [-Context] <String> [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>]
  • 37.
    .NET Core Use-DbContext Entity FrameworkCore Package Manager Console PARAMETERS -Context <String> Specifies the DbContext to use. -Project <String> Specifies the project to use. If omitted, the default project is used. -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used.
  • 38.
    .NET Core Using EFCore commands and EF 6 commands side-by-side Entity Framework Core Package Manager Console EF Core commands do not work on EF 6 or earlier version of EF. However, EF Core re- uses some of the same command names from these earlier versions. These commands can be installed side-by-side, however, EF does not automatically know which version of the command to use. This is solved by prefixing the command with the module name. The EF 6 commands PowerShell module is named “EntityFramework”, and the EF Core module is named “EntityFrameworkCore”. Without the prefix, PowerShell may call the wrong version of the command.
  • 39.
    .NET Core Using EFCore commands and EF 6 commands side-by-side Entity Framework Core Package Manager Console
  • 40.
    .NET Core Common Errors- Error: “No parameterless constructor was found” Entity Framework Core Package Manager Console Design-time tools attempt to automatically find how your application creates instances of your DbContext type. If EF cannot find a suitable way to initialize your DbContext, you may encounter this error. No parameterless constructor was found on 'TContext'. Either add a parameterless constructor to 'TContext' or add an implementation of 'IDbContextFactory<TContext>' in the same assembly as 'TContext'. As the error message suggests, one solution is to add an implementation of IDbContextFactory<TContext> to the current project. See Using IDbContextFactory<TContext> for an example of how to create this factory.
  • 41.
    .NET Core .NET CoreCLI Entity Framework Core .NET Core CLI Installation Prerequisites EF command-line tools requires .NET Core CLI Preview 2 or newer. Supported Frameworks • .NET Framework 4.5.1 and newer. (“net451”, “net452”, “net46”, etc.) • .NET Core App 1.0. (“netcoreapp1.0”)
  • 42.
    .NET Core .NET CoreCLI Entity Framework Core .NET Core CLI Install by editing project.json EF command-line tools for .NET Core CLI are installed by manually editing project.json. 1. Add Microsoft.EntityFrameworkCore.Tools as a “tool” and Microsoft.EntityFrameworkCore.Design as a build-only dependency under “dependencies”. See sample project.json below. 2. Execute dotnet restore. If restore does not succeed, the command-line tools may not have installed correctly. The resulting project.json should include these items (in addition to your other project dependencies).
  • 43.
    .NET Core .NET CoreCLI Entity Framework Core .NET Core CLI
  • 44.
    .NET Core .NET CoreCLI Entity Framework Core .NET Core CLI A build-only dependency ("type": "build") means this dependency is local to the current project. For example, if Project A has a build only dependency and Project B depends on A, dotnet restore will not add A’s build-only dependencies into Project B.
  • 45.
    .NET Core .NET CoreCLI - Usage Entity Framework Core .NET Core CLI Commands can be run from the command line by navigating to the project directory and executing dotnet ef [subcommand]. To see usage, add --help to any command to see more information about parameters and subcommands.
  • 46.
    .NET Core .NET CoreCLI - dotnet-ef Entity Framework Core .NET Core CLI Usage: dotnet ef [options] [command] Options: -h|--help Show help information -p|--project <PROJECT> The project to target (defaults to the project in the current directory). Can be a path to a project.json or a project directory. -s|--startup-project <PROJECT> The path to the project containing Startup (defaults to the target project). Can be a path to a project.json or a project directory.
  • 47.
    .NET Core .NET CoreCLI - dotnet-ef Entity Framework Core .NET Core CLI -c|--configuration <CONFIGURATION> Configuration under which to load (defaults to Debug) -f|--framework <FRAMEWORK> Target framework to load from the startup project (defaults to the framework most compatible with .NETCoreApp,Version=v1.0). -b|--build-base-path <OUTPUT_DIR> Directory in which to find temporary outputs. -o|--output <OUTPUT_DIR> Directory in which to find outputs
  • 48.
    .NET Core .NET CoreCLI - dotnet-ef Entity Framework Core .NET Core CLI Commands: • database Commands to manage your database • dbcontext Commands to manage your DbContext types • migrations Commands to manage your migrations
  • 49.
    .NET Core .NET CoreCLI - dotnet-ef-database Entity Framework Core .NET Core CLI Usage: dotnet ef database [options] [command] Options: -h|--help Show help information -v|--verbose Enable verbose output Commands: drop Drop the database for specific environment update Updates the database to a specified migration
  • 50.
    .NET Core .NET CoreCLI - dotnet-ef-database-drop Entity Framework Core .NET Core CLI Usage: dotnet ef database drop [options] Options: -e|--environment <environment> The environment to use. If omitted, "Development" is used. -c|--context <context> The DbContext to use. If omitted, the default DbContext is used -f|--force Drop without confirmation -h|--help Show help information -v|--verbose Enable verbose output
  • 51.
    .NET Core .NET CoreCLI - dotnet-ef-database-update Entity Framework Core .NET Core CLI Usage: dotnet ef database update [arguments] [options] Arguments: [migration] The target migration. If '0', all migrations will be reverted. If omitted, all pending migrations will be applied
  • 52.
    .NET Core .NET CoreCLI - dotnet-ef-dbcontext Entity Framework Core .NET Core CLI Usage: dotnet ef dbcontext [options] [command] Options: -h|--help Show help information -v|--verbose Enable verbose output Commands: list List your DbContext types scaffold Scaffolds a DbContext and entity type classes for a specified database
  • 53.
    .NET Core .NET CoreCLI - dotnet-ef-dbcontext-list Entity Framework Core .NET Core CLI Usage: dotnet ef dbcontext list [options] Options: -e|--environment <environment> The environment to use. If omitted, "Development" is used. --json Use json output. JSON is wrapped by '//BEGIN' and '//END' -h|--help Show help information -v|--verbose Enable verbose output
  • 54.
    .NET Core .NET CoreCLI - dotnet-ef-dbcontext-scaffold Entity Framework Core .NET Core CLI Usage: dotnet ef dbcontext scaffold [arguments] [options] Arguments: [connection] The connection string of the database [provider] The provider to use. For example, Microsoft.EntityFrameworkCore.SqlServer
  • 55.
    .NET Core .NET CoreCLI - dotnet-ef-dbcontext-scaffold Entity Framework Core .NET Core CLI Options: -a|--data-annotations Use DataAnnotation attributes to configure the model where possible. If omitted, the output code will use only the fluent API. -c|--context <name> Name of the generated DbContext class. -f|--force Force scaffolding to overwrite existing files. Otherwise, the code will only proceed if no output files would be overwritten. -o|--output-dir <path> Directory of the project where the classes should be output. If omitted, the top-level project directory is used.
  • 56.
    .NET Core .NET CoreCLI - dotnet-ef-dbcontext-scaffold Entity Framework Core .NET Core CLI --schema <schema> Selects a schema for which to generate classes. -t|--table <schema.table> Selects a table for which to generate classes. -e|--environment <environment> The environment to use. If omitted, "Development" is used. -h|--help Show help information -v|--verbose Enable verbose output
  • 57.
    .NET Core .NET CoreCLI - dotnet-ef-migrations Entity Framework Core .NET Core CLI Usage: dotnet ef migrations [options] [command] Options: -h|--help Show help information -v|--verbose Enable verbose output Commands: add Add a new migration list List the migrations remove Remove the last migration script Generate a SQL script from migrations
  • 58.
    .NET Core .NET CoreCLI - dotnet-ef-migrations-add Entity Framework Core .NET Core CLI Usage: dotnet ef migrations add [arguments] [options] Arguments: [name] The name of the migration
  • 59.
    .NET Core .NET CoreCLI - dotnet-ef-migrations-add Entity Framework Core .NET Core CLI Options: -o|--output-dir <path> The directory (and sub-namespace) to use. If omitted, "Migrations" is used. Relative paths are relative the directory in which the command is executed. -c|--context <context> The DbContext to use. If omitted, the default DbContext is used -e|--environment <environment> The environment to use. If omitted, "Development" is used. --json Use json output. JSON is wrapped by '//BEGIN' and '//END' -h|--help Show help information -v|--verbose Enable verbose output
  • 60.
    .NET Core .NET CoreCLI - dotnet-ef-migrations-add Entity Framework Core .NET Core CLI Options: -o|--output-dir <path> The directory (and sub-namespace) to use. If omitted, "Migrations" is used. Relative paths are relative the directory in which the command is executed. -c|--context <context> The DbContext to use. If omitted, the default DbContext is used -e|--environment <environment> The environment to use. If omitted, "Development" is used. --json Use json output. JSON is wrapped by '//BEGIN' and '//END' -h|--help Show help information -v|--verbose Enable verbose output
  • 61.