[英]Asp.Net MVC - Access to Postgresql with Entity Framework + Npgsql.Entityframework
我正在创建一个使用 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
),但在 base 中的数据表中没有看到任何记录 - DbSet BaseArticle 的计数等于 0。同时记录在那里。 我在哪里可以有错误?
还有 - 在 ASP.NET MVC 中一般不可能实现应用程序各部分之间的松散耦合? 例如 - 我创建了 ASP.NET MVC 应用程序并在单独的库中执行对数据库的访问类。 但是我必须在主项目中指明来自 Nuget 的包的链接。 我怎么能避免呢?
为了解决我的问题,我需要在上下文的构造函数中打开与 base 的连接:
this.Database.Connection.Open();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.