当前位置: 首页 > 工具软件 > efcore.pg > 使用案例 >

.net core EF 连接 PostgreSQL

贺自明
2023-12-01

 引入包


using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Npgsql.EntityFrameworkCore.PostgreSQL;

 

EF 所需的Context

    public class PostgreSQLContent : DbContext
    {
        public PostgreSQLContent(DbContextOptions<PostgreSQLContent> options) : base(options)
        {

        }

        public DbSet<TestTable> TestTable { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TestTable>(entity =>
            {
                entity.ToTable("test_table");
            });
        }
    }

实体Entity

    public class TestTable
    {
        public int id { get; set; }
        public DateTime updatetime { get; set; }
        public String name { get; set; }

    }

连接

 string conStr = "Host=xxxx;Username=postgres;Password=xxxx;Database=test_pg";

//不用注入
            DbContextOptions<PostgreSQLContent> dbContextOption = new DbContextOptions<PostgreSQLContent>();
            DbContextOptionsBuilder<PostgreSQLContent> dbContextOptionBuilder = new DbContextOptionsBuilder<PostgreSQLContent>(dbContextOption);
            var db = new PostgreSQLContent(dbContextOptionBuilder.UseNpgsql(conStr).Options);


//使用注入
            //IServiceCollection services = new ServiceCollection();
            //services.AddDbContext<PostgreSQLContent>(option => option.UseNpgsql(conStr));
            //var db = services.BuildServiceProvider().GetService<PostgreSQLContent>();


//插入
    db.TestTable.Add(new PostgreSQLTest.Models.TestTable() { id = 21, name = "teset_xiajun", updatetime = DateTime.Now });
            db.SaveChanges();
//获取数据
            var ent = db.TestTable.Where(s => s.id == 21).FirstOrDefault();

 

 类似资料: