【问题标题】:How to make database connectivity in ASP.NET core with PostgreSQL?如何使用 PostgreSQL 在 ASP.NET 核心中建立数据库连接?
【发布时间】:2022-01-25 02:12:34
【问题描述】:

如何在 ASP.NET Core 中使用 postgres SQL 建立数据库连接?

【问题讨论】:

    标签: sql postgresql asp.net-core database-connection


    【解决方案1】:

    Question: How to make database connection in ASP.NET core with postgres SQL ?

    有两种方法可以将postgresql 数据库与asp.net core 项目一起添加。

    使用以下方式:

    • ADO.net connection provider
    • Nuget extension: Npgsql.EntityFrameworkCore.PostgreSQL

    ADO.net connection provider

    这里只需要NpgsqlConnection 连接构建器类,它将在Postgre sql 数据库服务器上执行您的sql。请参见下面的示例:

    C# ASP.NET Core & Postgre SQL Ado.net example:

      NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres;Password=pwd;Database=postgres;");
        
        conn.Open();
        
        // Passing PostGre SQL Function Name
        NpgsqlCommand command = new NpgsqlCommand("EXE GetEmployeePrintInfo", conn);
        
        // Execute the query and obtain a result set
        NpgsqlDataReader reader = command.ExecuteReader();
        
        // Reading from the database rows
        List<string> listOfManager = new List<string>();
    
        while (reader.Read())
        {
            string WSManager = reader["WSManager"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
            listOfManager.Add(WSManager);
        }
        reader.Close();
    
        command.Dispose();
        conn.Close();
    

    Npgsql.EntityFrameworkCore.PostgreSQL:

    您必须使用Visual studioNuget extensionmanage Nuget Packages 添加到项目引用中。 Entity framework core 为许多数据库提供商提供此功能。只需在visual studio 上按照以下步骤操作即可

    ConfigureServices in startup.cs: 成功添加Nuget package 后,您必须在startup.cs 下的项目ConfigureServices 上更新以下代码

            services.AddDbContext<YourDatabaseContextClassName>(options =>
            options.UseNpgsql(Configuration.GetConnectionString("YourDatabaseContextStringNameFromAppsettings")));
    

    Note: 如果您需要entityframeworkPostgre SQL 的任何示例implementation you can have look here

    如需进一步帮助,您可以查看official document here。希望它能为您提供相应的指导。

    【讨论】:

      【解决方案2】:

      使用 Npgsql EF Core 提供程序,添加对 Npgsql.EntityFrameworkCore.PostgreSQL 的依赖。您可以按照通用 EF Core 入门文档中的说明进行操作。 https://www.npgsql.org/efcore/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-11
        • 2015-12-30
        相关资源
        最近更新 更多