简体   繁体   English

在带有Npgsql的Asp.net 5(vnext)中使用Postgres

[英]Using Postgres in Asp.net 5 (vnext) with Npgsql

I have configured my app to connect to a Postgres database, but when loading some data to it, it gives me an error. 我已经将我的应用程序配置为连接到Postgres数据库,但是在向其中加载一些数据时,它给了我一个错误。

First, here is what I include in project.json: 首先,这是我包含在project.json中的内容:

"EntityFramework7.Npgsql": "3.1.0-rc1-1",

and in Startup.cs class: 并在Startup.cs类中:

services.AddEntityFramework()
            .AddNpgsql()
            .AddDbContext<ApplicationDbContext>(options =>
                    options.UseNpgsql(Configuration["Data:DefaultConnection:ConnectionString"]));

here is my connection string: 这是我的连接字符串:

Server=127.0.0.1;Port=5432;Database=test1;User Id=postgres;Password=mypass123

The dnx command to update database works very well, but I had to create manually the "__EFMigrationsHistory" table. dnx命令更新数据库效果很好,但是我必须手动创建“ __EFMigrationsHistory”表。

The problem is the following error, when executing context.SaveChanges : 问题是执行context.SaveChanges时出现以下错误:

{Microsoft.Data.Entity.DbUpdateException: An error occurred while updating the entries. {Microsoft.Data.Entity.DbUpdateException:更新条目时发生错误。 See the inner exception for details. 有关详细信息,请参见内部异常。 ---> Npgsql.NpgsqlException: 23502: null value in column "Id" violates not-null constraint em Npgsql.NpgsqlConnector.DoReadSingleMessage(DataRowLoadingMode dataRowLoadingMode, Boolean returnNullForAsyncMessage, Boolean isPrependedMessage) em Npgsql.NpgsqlConnector.ReadSingleMessageWithPrepended(DataRowLoadingMode dataRowLoadingMode, Boolean returnNullForAsyncMessage) em Npgsql.NpgsqlConnector.ReadSingleMessage(DataRowLoadingMode dataRowLoadingMode) em Npgsql.NpgsqlDataReader.ReadMessage() em Npgsql.NpgsqlDataReader.Init() em Npgsql.NpgsqlCommand.Execute(CommandBehavior behavior) em Npgsql.NpgsqlCommand.ExecuteDbDataReaderInternal(CommandBehavior behavior) em Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior) em System.Data.Common.DbCommand.ExecuteReader() em Microsoft.Data.Entity.Storage.Internal.RelationalCommand.<>c__DisplayClass17_0.b__0(DbCommand cmd, IRelationalConnection con) em Microsoft.Data.Entity.Storage.Internal.RelationalCommand.Execute[T](IRelationalConnect ---> Npgsql.NpgsqlException:23502:“ Id”列中的空值违反了非空约束em )em Npgsql.NpgsqlConnector.ReadSingleMessage(DataRowLoadingMode dataRowLoadingMode)em Npgsql.NpgsqlDataReader.ReadMessage()em Npgsql.NpgsqlDataReader.Init()em Npgsql.NpgsqlCommand.Execute(CommandBehavior行为)em Npgsql.NpgsqlCommand.Indbternal() NpgsqlCommand.ExecuteDbDataReader(CommandBehavior行为)em System.Data.Common.DbCommand.ExecuteReader()em Microsoft.Data.Entity.Storage.Internal.RelationalCommand。<> c__DisplayClass17_0.b__0(DbCommand cmd,IRelationalConnection con)em Microsoft.Data.Entity .Storage.Internal.RelationalCommand.Execute [T](IRelationalConnect ion connection, Func 3 action, String executeMethod, Boolean openConnection, Boolean closeConnection) em Microsoft.Data.Entity.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, Boolean manageConnection) em Microsoft.Data.Entity.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) --- Fim do rastreamento de pilha de exceções internas --- em Microsoft.Data.Entity.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) em Microsoft.Data.Entity.Update.Internal.BatchExecutor.Execute(IEnumerable 1 commandBatches, IRelationalConnection connection) em Microsoft.Data.Entity.Storage.RelationalDatabase.SaveChanges(IReadOnlyList 1 entries) em Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList 1 entriesToSave) em Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess) em Microsoft.Data.Entity.DbContext.SaveChanges(Boolean acceptAll 离子连接,功能3 action, String executeMethod, Boolean openConnection, Boolean closeConnection) em Microsoft.Data.Entity.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, Boolean manageConnection) em Microsoft.Data.Entity.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) --- Fim do rastreamento de pilha de exceções internas --- em Microsoft.Data.Entity.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) em Microsoft.Data.Entity.Update.Internal.BatchExecutor.Execute(IEnumerable 1 commandBatches,IRelationalConnection连接),Microsoft.Data.Entity.Storage.RelationalDatabase.SaveChanges(IReadOnlyList 1 entries) em Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList 1 entries) em Microsoft.Data.Entity.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList保存)和Microsoft.Data.Entity.ChangeTracking。 Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)em Microsoft.Data.Entity.DbContext.SaveChanges(Boolean acceptAll ChangesOnSuccess) em Microsoft.Data.Entity.DbContext.SaveChanges() em SQLite.Migrations.Seed.CriaEndereco() na F:\\Dados\\Documents\\Visual Studio 2015\\Projects\\SQLite\\src\\SQLite\\Migrations\\Seed.cs:linha 73 em SQLite.Migrations.Seed.Execute(IServiceProvider applicationServices) na F:\\Dados\\Documents\\Visual Studio 2015\\Projects\\SQLite\\src\\SQLite\\Migrations\\Seed.cs:linha 36 em SQLite.Startup.CreateSampleData(IServiceProvider applicationServices) na F:\\Dados\\Documents\\Visual Studio 2015\\Projects\\SQLite\\src\\SQLite\\Startup.cs:linha 138 em SQLite.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) na F:\\Dados\\Documents\\Visual Studio 2015\\Projects\\SQLite\\src\\SQLite\\Startup.cs:linha 128} ChangesOnSuccess)em Microsoft.Data.Entity.DbContext.SaveChanges()em SQLite.Migrations.Seed.CriaEndereco()na F:\\ Dados \\ Documents \\ Visual Studio 2015 \\ Projects \\ SQLite \\ src \\ SQLite \\ Migrations \\ Seed.cs: linha 73 em SQLite.Migrations.Seed.Execute(IServiceProvider applicationServices)不适用F:\\ Dados \\ Documents \\ Visual Studio 2015 \\ Projects \\ SQLite \\ src \\ SQLite \\ Migrations \\ Seed.cs:linha 36 em SQLite.Startup.CreateSampleData(IServiceProvider F:\\ Dados \\ Documents \\ Visual Studio 2015 \\ Projects \\ SQLite \\ src \\ SQLite \\ Startup.cs:linha 138 em SQLite.Startup.Configure(IApplicationBuilder应用程序,IHostingEnvironment env,ILoggerFactory loggerFactory)无F:\\ Dados \\ Documents \\ Visual Studio 2015 \\ Projects \\ SQLite \\ src \\ SQLite \\ Startup.cs:linha 128}

The Id columns should be assigned by entity, or not ? Id列应该由实体分配,还是不?

Same code works in SqlServer. 相同的代码在SqlServer中工作。

update 更新

Here is the SqlServer table schema: 这是SqlServer表架构:

CREATE TABLE [dbo].[Ufs] (
    [Id]    INT           IDENTITY (1, 1) NOT NULL,
    [Nome]  NVARCHAR (70) NOT NULL,
    [Sigla] NVARCHAR (2)  NOT NULL,
    CONSTRAINT [PK_Uf] PRIMARY KEY CLUSTERED ([Id] ASC)
);

and here Postgres: 在这里Postgres:

CREATE TABLE public."Ufs"
(
  "Id" integer NOT NULL,
  "Nome" text NOT NULL,
  "Sigla" text NOT NULL,
  CONSTRAINT "PK_Uf" PRIMARY KEY ("Id")
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public."Ufs"
  OWNER TO postgres;

All these codes was automatically generated by migrations. 所有这些代码都是通过迁移自动生成的。

It looks like you generated you Postgres database using SqlServer migrations. 看起来您是使用SqlServer迁移生成了Postgres数据库的。

I recommend you revert and remove all migrations and add migrations again. 我建议您还原并删除所有迁移,然后再次添加迁移。

The "Id" Column in your Postgres Database should be a "Serial" type or something similar. Postgres数据库中的“ Id”列应为“ Serial”类型或类似名称。

Postgres "Integer" type is not an auto-incremented type. Postgres的“整数”类型不是自动递增的类型。 By default it's the database's role to assign ids. 默认情况下,分配ID是数据库的角色。

Try adding this annotation above your "Id" Property. 尝试将此注释添加到“ Id”属性上方。

DatabaseGenerated(DatabaseGeneratedOption.Identity)

rel. 相对。 This is a related question 这是一个相关的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM