« Entity Framework Core 7 » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
Ligne 49 : Ligne 49 :


= Connection string =
= Connection string =
* [[Asp.net_core_5#Configuration|Configuration file and secrets]]
* [[Asp.net_core_7#Configuration|Configuration file and secrets]]


<filebox fn='appsettings.json'>
<filebox fn='appsettings.json'>

Version du 28 juin 2023 à 21:35

Entity Framework Core Tools

Powershell.svg
# test if Entity Framework Core Tools has been installed
dotnet ef
# be sure to run the previous command in the folder of the project where EF has been added

# dotnet ef must be installed as a global or local tool
dotnet tool install --global dotnet-ef
# installed in ~/.dotnet/tools
# Add ~/.dotnet/tools to PATH

# update
dotnet tool update --global dotnet-ef
Visual Studio
  • View → Other Windows → Package Manager Console
  • Default Project = the one containing the entity configurations
  • Startup Project = the one containing the sql server configuration

Add Entity Framework Core package

Bash.svg
# sql server
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design

# mysql
dotnet add package Pomelo.EntityFrameworkCore.MySql
dotnet add package Microsoft.EntityFrameworkCore.Design

Data Providers

Provider Package NuGet Connection String
SQL Server Microsoft.EntityFrameworkCore.SqlServer Server=(localdb)\\MSSQLLocalDB;Database=MyDb;Integrated Security=True;MultipleActiveResultSets=True;
Server=localhost;Database=MyDb;User=sa;Password=pwd;
MySQL / MariaDB Pomelo.EntityFrameworkCore.MySql server=localhost;database=MyDb;user=root;password=pwd
PostgreSQL Npgsql.EntityFrameworkCore.PostgreSQL Host=localhost;Database=MyDb;Username=root;Password=pwd
InMemory Microsoft.EntityFrameworkCore.InMemory databaseName: "test_database"
Sqlite Microsoft.EntityFrameworkCore.Sqlite Data Source=/tmp/file.db

Connection string

appsettings.json
{
  "ConnectionStrings": {
    "MariaDb": "server=localhost;database=test;user=test;password=***"
  }
}

Dependency injection (ASP.Net Core)

MariaDb / MySql

Program.cs
var connectionString = builder.Configuration.GetConnectionString("MariaDb");
var serverVersion = new MariaDbServerVersion(new Version(10, 11, 4));

builder.Services.AddDbContext<MyAppContext>(
    dbContextOptions => dbContextOptions
        .UseMySql(connectionString, serverVersion)
        // TODO The following three options help with debugging, but should be changed or removed for production.
        .LogTo(Console.WriteLine, LogLevel.Information)
        .EnableSensitiveDataLogging()
        .EnableDetailedErrors());

DbContext OnConfiguring

DataAccess/MyAppContext.cs
public class MyAppContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("server=localhost;database=test;user=test;password=***"); // hard-coded connection string
        optionsBuilder.UseMySql("name=ConnectionStrings:MariaDb", ServerVersion.Parse("10.11.4-mariadb")); // connection string in the appsettings.json
        optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["SqlServerConnectionString"].ConnectionString); // WPF

Constructor parameter

Cs.svg
var builder = new ConfigurationBuilder()
    .AddUserSecrets<MyAppContextFactory>();
var configuration = builder.Build();

var connectionStringBuilder = new SqlConnectionStringBuilder("server=localhost;database=test;user=test;");
connectionStringBuilder.Password = configuration["DbPassword"];

var connectionString = connectionStringBuilder.ConnectionString;
var connectionString = "server=localhost;database=test;user=test;password=****";

var contextOptions = new DbContextOptionsBuilder<MyAppContext>()
    .UseMySql(
        connectionString,
        mySqlOptions => mySqlOptions.ServerVersion("10.5.8-mariadb"))
    .Options;

using var context = new MyAppContext(contextOptions);
DataAccess/MyAppContext.cs
public class MyAppContext : DbContext
{
    public MyAppContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    { }