using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Npgsql.EntityFrameworkCore.PostgreSQL;
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");
});
}
}
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();