winform 连接postgres数据库 EF codefirst——方法一

1,安装类库

2,新建数据库实体类

 [Table("hello")]
    public class Hello
    {
        [Key]
        [Column("hi")]
        [Required]
        public Guid? Hi { get; set; }
        [Column("prop")]
        public string MyProperty { get; set; }
    }

 

3,新建数据库上下文

   public class Hello_DBContext : DbContext
    {
        public Hello_DBContext() : base("DefaultConnection") { }//“DefaultConnection"对应App.config中的连接字符串

        public DbSet<Hello> Hello { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();//去S
        }
    }

4,"工具" ——> "NuGet程序管理器"——>"程序包管理控制台"

enable-migrations  

add-migration 

update-database

该方法会把表添加到用户dbo下,而非常用的public下

错误1:No migrations configuration type was found in the assembly 'WindowsFormsApp1'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).

解决:项目中没有Configuration.cs文件,执行enable-migrations 

错误2:No Entity Framework provider found for the ADO.NET provider with invariant name 'Npgsql'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.

解决:在NuGet中安装EntityFrameWork6.Npgsql

错误3:An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file. See http://go.microsoft.com/fwlink/?LinkId=386386 for information on DbContext and connections. See the inner exception for details of the failure.

解决:在连接字符串没错的情况下,在NuGet中安装:Npgsql.EntityFrameworkCore.PostgreSQL

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页