人本善良

导航

ef pgsql

Npgsql Entity Framework Core Provider

stable unstable next patch build gitter

Npgsql has an Entity Framework (EF) Core provider. It behaves like other EF Core providers (e.g. SQL Server), so the general EF Core docs apply here as well. If you're just getting started with EF Core, those docs are the best place to start.

Development happens in the Npgsql.EntityFrameworkCore.PostgreSQL repository, all issues should be reported there.

Configuring the project file

To use the Npgsql EF Core provider, add a dependency on Npgsql.EntityFrameworkCore.PostgreSQL. You can follow the instructions in the general EF Core Getting Started docs.

Below is a .csproj file for a console application that uses the Npgsql EF Core provider:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.3" />
  </ItemGroup>
</Project>

Defining a DbContext

using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

namespace ConsoleApp.PostgreSQL
{
    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseNpgsql("Host=my_host;Database=my_db;Username=my_user;Password=my_pw");
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }

        public List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
}

Additional configuration for ASP.NET Core applications

Consult this tutorial for general information on how to make ASP.NET work with EF Core. For Npgsql specifically, simply place the following in your ConfigureServices method in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // Other DI initializations

    services.AddDbContext<BloggingContext>(options =>
            options.UseNpgsql(Configuration.GetConnectionString("BloggingContext")));
}

Using an Existing Database (Database-First)

The Npgsql EF Core provider also supports reverse-engineering a code model from an existing PostgreSQL database ("database-first"). To do so, use dotnet CLI to execute the following:

dotnet ef dbcontext scaffold "Host=my_host;Database=my_db;Username=my_user;Password=my_pw" Npgsql.EntityFrameworkCore.PostgreSQL




entityframwork cli 准备

Entity Framework Core tools reference - .NET Core CLI

The command-line interface (CLI) tools for Entity Framework Core perform design-time development tasks. For example, they create migrations, apply migrations, and generate code for a model based on an existing database. The commands are an extension to the cross-platform dotnet command, which is part of the .NET Core SDK. These tools work with .NET Core projects.

When using Visual Studio, consider using the Package Manager Console tools in lieu of the CLI tools. Package Manager Console tools automatically:

  • Works with the current project selected in the Package Manager Console without requiring that you manually switch directories.
  • Opens files generated by a command after the command is completed.
  • Provides tab completion of commands, parameters, project names, context types, and migration names.

Installing the tools

dotnet ef can be installed as either a global or local tool. Most developers prefer installing dotnet ef as a global tool using the following command:

.NET Core CLI
dotnet tool install --global dotnet-ef

To use it as a local tool, restore the dependencies of a project that declares it as a tooling dependency using a tool manifest file.

Update the tool tool using the following command:

.NET Core CLI
dotnet tool update --global dotnet-ef

Before you can use the tools on a specific project, you'll need to add the Microsoft.EntityFrameworkCore.Design package to it.

.NET Core CLI
dotnet add package Microsoft.EntityFrameworkCore.Design

Verify installation

Run the following commands to verify that EF Core CLI tools are correctly installed:

.NET Core CLI
dotnet ef

The output from the command identifies the version of the tools in use:

Output

                     _/\__
               ---==/    \\
         ___  ___   |.    \|\
        | __|| __|  |  )   \\\
        | _| | _|   \_/ |  //|\\
        |___||_|       /   \\\/\\

Entity Framework Core .NET Command-line Tools 2.1.3-rtm-32065

<Usage documentation follows, not shown.>

Update the tools

Use dotnet tool update --global dotnet-ef to update the global tools to the latest available version. If you have the tools installed locally in your project use dotnet tool update dotnet-ef. Install a specific version by appending --version <VERSION> to your command. See the Update section of the dotnet tool documentation for more details.

Using the tools

Before using the tools, you might have to create a startup project or set the environment.

Target project and startup project

The commands refer to a project and a startup project.

  • The project is also known as the target project because it's where the commands add or remove files. By default, the project in the current directory is the target project. You can specify a different project as target project by using the --project option.

  • The startup project is the one that the tools build and run. The tools have to execute application code at design time to get information about the project, such as the database connection string and the configuration of the model. By default, the project in the current directory is the startup project. You can specify a different project as startup project by using the --startup-project option.

The startup project and target project are often the same project. A typical scenario where they are separate projects is when:

  • The EF Core context and entity classes are in a .NET Core class library.
  • A .NET Core console app or web app references the class library.

It's also possible to put migrations code in a class library separate from the EF Core context.

Other target frameworks

The CLI tools work with .NET Core projects and .NET Framework projects. Apps that have the EF Core model in a .NET Standard class library might not have a .NET Core or .NET Framework project. For example, this is true of Xamarin and Universal Windows Platform apps. In such cases, you can create a .NET Core console app project whose only purpose is to act as startup project for the tools. The project can be a dummy project with no real code — it is only needed to provide a target for the tooling.

Why is a dummy project required? As mentioned earlier, the tools have to execute application code at design time. To do that, they need to use the .NET Core runtime. When the EF Core model is in a project that targets .NET Core or .NET Framework, the EF Core tools borrow the runtime from the project. They can't do that if the EF Core model is in a .NET Standard class library. The .NET Standard is not an actual .NET implementation; it's a specification of a set of APIs that .NET implementations must support. Therefore .NET Standard is not sufficient for the EF Core tools to execute application code. The dummy project you create to use as startup project provides a concrete target platform into which the tools can load the .NET Standard class library.

ASP.NET Core environment

To specify the environment for ASP.NET Core projects, set the ASPNETCORE_ENVIRONMENT environment variable before running commands.

Common options

COMMON OPTIONS
OptionShortDescription
--json   Show JSON output.
--context <DBCONTEXT> -c The DbContext class to use. Class name only or fully qualified with namespaces. If this option is omitted, EF Core will find the context class. If there are multiple context classes, this option is required.
--project <PROJECT> -p Relative path to the project folder of the target project. Default value is the current folder.
--startup-project <PROJECT> -s Relative path to the project folder of the startup project. Default value is the current folder.
--framework <FRAMEWORK>   The Target Framework Moniker for the target framework. Use when the project file specifies multiple target frameworks, and you want to select one of them.
--configuration <CONFIGURATION>   The build configuration, for example: Debug or Release.
--runtime <IDENTIFIER>   The identifier of the target runtime to restore packages for. For a list of Runtime Identifiers (RIDs), see the RID catalog.
--no-build   Don't build the project. Intended to be used when the build is up-to-date.
--help -h Show help information.
--verbose -v Show verbose output.
--no-color   Don't colorize output.
--prefix-output   Prefix output with level.

Starting in EF Core 5.0, any additional arguments are passed to the application.

dotnet ef database drop

Drops the database.

Options:

DOTNET EF DATABASE DROP
OptionShortDescription
--force -f Don't confirm.
--dry-run   Show which database would be dropped, but don't drop it.

The common options are listed above.

dotnet ef database update

Updates the database to the last migration or to a specified migration.

Arguments:

DOTNET EF DATABASE UPDATE
ArgumentDescription
<MIGRATION> The target migration. Migrations may be identified by name or by ID. The number 0 is a special case that means before the first migration and causes all migrations to be reverted. If no migration is specified, the command defaults to the last migration.

Options:

DOTNET EF DATABASE UPDATE
OptionDescription
--connection <CONNECTION> The connection string to the database. Defaults to the one specified in AddDbContext or OnConfiguring. Added in EF Core 5.0.

The common options are listed above.

The following examples update the database to a specified migration. The first uses the migration name and the second uses the migration ID and a specified connection:

.NET Core CLI
dotnet ef database update InitialCreate
dotnet ef database update 20180904195021_InitialCreate --connection your_connection_string

dotnet ef dbcontext info

Gets information about a DbContext type.

The common options are listed above.

dotnet ef dbcontext list

Lists available DbContext types.

The common options are listed above.

dotnet ef dbcontext scaffold

Generates code for a DbContext and entity types for a database. In order for this command to generate an entity type, the database table must have a primary key.

Arguments:

DOTNET EF DBCONTEXT SCAFFOLD
ArgumentDescription
<CONNECTION> The connection string to the database. For ASP.NET Core 2.x projects, the value can be name=<name of connection string>. In that case the name comes from the configuration sources that are set up for the project.
<PROVIDER> The provider to use. Typically this is the name of the NuGet package, for example: Microsoft.EntityFrameworkCore.SqlServer.

Options:

DOTNET EF DBCONTEXT SCAFFOLD
OptionShortDescription
--data-annotations -d Use attributes to configure the model (where possible). If this option is omitted, only the fluent API is used.
--context <NAME> -c The name of the DbContext class to generate.
--context-dir <PATH>   The directory to put the DbContext class file in. Paths are relative to the project directory. Namespaces are derived from the folder names.
--context-namespace <NAMESPACE>   The namespace to use for the generated DbContext class. Note: overrides --namespace. Added in EF Core 5.0.
--force -f Overwrite existing files.
--output-dir <PATH> -o The directory to put entity class files in. Paths are relative to the project directory.
--namespace <NAMESPACE> -n The namespace to use for all generated classes. Defaults to generated from the root namespace and the output directory. Added in EF Core 5.0.
--schema <SCHEMA_NAME>...   The schemas of tables to generate entity types for. To specify multiple schemas, repeat --schema for each one. If this option is omitted, all schemas are included.
--table <TABLE_NAME>... -t The tables to generate entity types for. To specify multiple tables, repeat -t or --table for each one. If this option is omitted, all tables are included.
--use-database-names   Use table and column names exactly as they appear in the database. If this option is omitted, database names are changed to more closely conform to C# name style conventions.
--no-onconfiguring   Suppresses generation of the OnConfiguring method in the generated DbContext class. Added in EF Core 5.0.
--no-pluralize   Don't use the pluralizer. Added in EF Core 5.0

The common options are listed above.

The following example scaffolds all schemas and tables and puts the new files in the Models folder.

.NET Core CLI
dotnet ef dbcontext scaffold "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

The following example scaffolds only selected tables and creates the context in a separate folder with a specified name and namespace:

.NET Core CLI
dotnet ef dbcontext scaffold "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models -t Blog -t Post --context-dir Context -c BlogContext --context-namespace New.Namespace

dotnet ef dbcontext script

Generates a SQL script from the DbContext. Bypasses any migrations. Added in EF Core 3.0.

Options:

DOTNET EF DBCONTEXT SCRIPT
OptionShortDescription
--output <FILE> -o The file to write the result to.

The common options are listed above.

dotnet ef migrations add

Adds a new migration.

Arguments:

DOTNET EF MIGRATIONS ADD
ArgumentDescription
<NAME> The name of the migration.

Options:

DOTNET EF MIGRATIONS ADD
OptionShortDescription
--output-dir <PATH> -o The directory use to output the files. Paths are relative to the target project directory. Defaults to "Migrations".
--namespace <NAMESPACE> -n The namespace to use for the generated classes. Defaults to generated from the output directory. Added in EF Core 5.0.

The common options are listed above.

dotnet ef migrations list

Lists available migrations.

Options:

DOTNET EF MIGRATIONS LIST
OptionDescription
--connection <CONNECTION> The connection string to the database. Defaults to the one specified in AddDbContext or OnConfiguring. Added in EF Core 5.0.
--no-connect Don't connect to the database. Added in EF Core 5.0.

The common options are listed above.

dotnet ef migrations remove

Removes the last migration (rolls back the code changes that were done for the migration).

Options:

DOTNET EF MIGRATIONS REMOVE
OptionShortDescription
--force -f Revert the migration (roll back the changes that were applied to the database).

The common options are listed above.

dotnet ef migrations script

Generates a SQL script from migrations.

Arguments:

DOTNET EF MIGRATIONS SCRIPT
ArgumentDescription
<FROM> The starting migration. Migrations may be identified by name or by ID. The number 0 is a special case that means before the first migration. Defaults to 0.
<TO> The ending migration. Defaults to the last migration.

Options:

DOTNET EF MIGRATIONS SCRIPT
OptionShortDescription
--output <FILE> -o The file to write the script to.
--idempotent -i Generate a script that can be used on a database at any migration.
--no-transactions   Don't generate SQL transaction statements. Added in EF Core 5.0.

The common options are listed above.

The following example creates a script for the InitialCreate migration:

.NET Core CLI
dotnet ef migrations script 0 InitialCreate

The following example creates a script for all migrations after the InitialCreate migration.

.NET Core CLI
dotnet ef migrations script 20180904195021_InitialCreate

Additional resources

Feedback

 

posted on 2020-10-21 14:39  简简单单2018  阅读(156)  评论(0编辑  收藏  举报