Asp.Net MVC - 使用Entity Framework + Npgsql.Entityframework访问PostgreSQL

3

我正在创建一个使用PostgreSql数据库的ASP.NET MVC应用程序。模型类位于不同的类库中。为了访问数据库,我在类库中使用了来自Nuget的Entity Framework + Npgsql.Entityframework。同时,我也将相同的链接添加到主项目中。配置设置位于主项目的web.config文件中:

<configSections>
    <section name="entityFramework" 
             type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
             requirePermission="false" />
</configSections>
<entityFramework>
    <defaultConnectionFactory type="Npgsql.NpgsqlServices, Npgsql.EntityFramework" />
    <providers>
        <provider invariantName="Npgsql" 
                  type="Npgsql.NpgsqlServices, Npgsql.EntityFramework" />
    </providers>
</entityFramework>
<connectionStrings>
    <add name="NpgsqlContext" 
         providerName="Npgsql" 
         connectionString="Server=127.0.0.1;User Id=BaseId;Password=BasePass;Port=5432;Database=Base;" />
</connectionStrings>
<system.data>
    <DbProviderFactories>
        <add name="Npgsql Data Provider" 
             invariant="Npgsql"
             support="FF" 
             description=".Net Framework Data Provider for Postgresql"
             type="Npgsql.NpgsqlFactory, Npgsql" />
    </DbProviderFactories>
</system.data>

我在pgAdmin中创建了数据库和一些表。为了访问这些数据库和表,我使用了类(例如):

public class NpgsqlContext : DbContext
{
    public NpgsqlContext() : base(nameOrConnectionString: "NpgsqlContext") 
    {
    }
}

        public DbSet<BaseArticle> BaseArticles { get; set; }
    }

    [Table("ARTICLE", Schema = "public")]
    public class BaseArticle
    {
        [Key]
        [Column("ID")]
        public int Id { get; set; }

        [Column("DATETIME")]
        public DateTime DateTime { get; set; }

        [Column("TITLE")]
        public string Title { get; set; }

        [Column("BODY")]
        public string Body { get; set; }
    }

NpgsqlContext对象通常会被创建并具有正确的连接字符串(PORT=5432;KRBSRVNAME=name;TIMEOUT=15;POOLING=True;MINPOOLSIZE=1;MAXPOOLSIZE=20;COMMANDTIMEOUT=20;COMPATIBLE=2.2.7.0;HOST=127.0.0.1;USER ID=BasePass;PASSWORD=BasePass;DATABASE=Base),但在数据库表中没有看到任何记录-DbSet BaseArticle的计数为0。与此同时,记录确实存在。我犯了哪些错误?

而且,在ASP.NET MVC中通常无法实现应用程序各部分之间的松散耦合?例如-我创建了ASP.NET MVC应用程序并将访问数据库的类移至单独的库中。但我不得不在主项目中指示Nuget包的链接。我该如何避免这种情况发生?

1个回答

1
为了解决我的问题,我需要在上下文的构造函数中打开与数据库的连接:
this.Database.Connection.Open();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接