官方介绍地址
http://www.npgsql.org/ef6/index.html
首先创建一个控制台应用程序 ,本例居于.NETFramework,Version=v4.6.1
安装包
EntityFramework6.Npgsql
先写一个业务类
using System; namespace EFCodeFirstConsole { public class Blog { public int Id { get; set; } public string Name { get; set; } public string Url { get; set; } public DateTime? CreateTime { get; set; } public double Double { get; set; } public float Float { get; set; } } }
然后创建一个继承自EF上下文的类
using System.Data.Entity; namespace EFCodeFirstConsole { public class EfDbContext : DbContext { public EfDbContext():base("name=PgsqlConnStr") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //EF 默认的schema 是dbo,但是PG默认是public,这里改一下 modelBuilder.HasDefaultSchema("public"); } public DbSet<Blog> Blogs { get; set; } } }
创建配置类
using Npgsql; using System.Data.Entity; namespace EFCodeFirstConsole { class NpgSqlConfiguration:DbConfiguration { public NpgSqlConfiguration() { var name = "Npgsql"; SetProviderFactory(providerInvariantName: name, providerFactory: NpgsqlFactory.Instance); SetProviderServices(providerInvariantName: name, provider: NpgsqlServices.Instance); SetDefaultConnectionFactory(connectionFactory: new NpgsqlConnectionFactory()); } } }
在配置文件中增加数据库配置
<connectionStrings> <add name="PgsqlConnStr" connectionString="Host=127.0.0.1;Port=5432;Database=EfDb;Username=dbuser;Password=dbpassword" providerName="Npgsql"/> </connectionStrings>
控制台Main方法创建数据库并插入数据
using System.Data.Entity; namespace EFCodeFirstConsole { class Program { static void Main(string[] args) { var Initializes = new DropCreateDatabaseAlways<EfDbContext>(); using (var efDbContext = new EfDbContext()) { Initializes.InitializeDatabase(efDbContext); } using (var efDbContext = new EfDbContext()) { efDbContext.Blogs.Add(new Blog { Name="Jeffcky", Url="http://www.qq.com" }); efDbContext.SaveChanges(); } } } }
参考:https://www.cnblogs.com/lyqf365/p/3978359.html