.net core EF 连接 PostgreSQL
程序员文章站
2024-01-04 12:48:10
...
引入包
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();
推荐阅读
-
.net core EF 连接 PostgreSQL
-
.Net Core + EF + mysql 从数据库生成实体
-
.net core EF Core调用存储过程的方式
-
(21)ASP.NET Core EF创建模型(关系)
-
.net core Webapi +EF
-
.NET Core 获取数据库上下文实例的方法和配置连接字符串
-
.net core EF Core调用存储过程的方式
-
.Net Core控制台&EFCore连接Mysql
-
(24)ASP.NET Core EF查询(查询的工作原理、跟踪与非跟踪查询)
-
(22)ASP.NET Core EF创建模型(索引、备用键、继承、支持字段)