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

博客介绍了使用WinForm Code First方式搭建数据库的步骤,包括安装类库、新建数据库实体类和上下文,以及通过NuGet程序管理器进行迁移和更新数据库。同时,针对搭建过程中出现的三种错误给出了解决办法,如执行命令、安装相关类库等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值