PostgreSQL使用EF Code First构建数据模型

1 注册EF Provider
PM> Install-Package EntityFramework6.Npgsql ~3.1.0

app.config或者web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="Npgsql" />
      <add name="Npgsql Data Provider" invariant="Npgsql" description=".Net Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7" support="FF" />
    </DbProviderFactories>
  </system.data>
</configuration>

2 创建数据库上下文
public class DefalutContext : DbContext
{
     public DefalutContext() : base(nameOrConnectionString: "Default")
     {
     }
}

3 连接字符串

<connectionStrings>
  <add name="Default" connectionString="host=localhost;user id=postgres;password=mw;database=postgres;Pooling=false;Timeout=300;CommandTimeout=300;" providerName="Npgsql" />
</connectionStrings>

 

4 使用迁移创建数据库

Add-Migration Initial

Update-Database

 

posted @ 2020-04-20 15:26  sulerzh  阅读(493)  评论(0编辑  收藏  举报