簡體   English   中英

無法在 Entity Framework Core 中播種數據

[英]Cannot seed data in Entity Framework Core

我無法將數據播種到我的 Postgres 數據庫中。

第一個 model 代表一個問題。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Envy.API.Entities
{
    public record Question
    {
        [Required]
        public Guid Id { get; init; }

        [Required]
        public DateTime CreatedDate { get; set; }

        [Required]
        public DateTime UpdatedDate { get; set; }

        [Required]
        public string Text { get; set; }

        [Required]
        public Guid UserId { get; set; }

        [Required]
        public User User { get; set; }

        public ICollection<Answer> Answers { get; set; }
    }
}

第二個代表一個問題的答案。

using System;
using System.ComponentModel.DataAnnotations;

namespace Envy.API.Entities
{
    public record Answer
    {
        [Required]
        public Guid Id { get; init; }

        [Required]
        public DateTime CreatedDate { get; set; }

        [Required]
        public DateTime UpdatedDate { get; set; }

        [Required]
        public string Text { get; set; }

        [Required]
        public Question Question { get; set; }

        [Required]
        public User User { get; set; }
    }
}

我在我的 Program.cs 文件中運行的 class 中創建了一個 function 來播種數據,它看起來像這樣。

public static async Task SeedQuestions(EnvyDbContext context)
{
    var questionData = await File.ReadAllTextAsync("Data/QuestionSeedData.json");
    var questions = JsonSerializer.Deserialize<List<Question>>(questionData);

    foreach (var question in questions)
    {
        question.CreatedDate = question.UpdatedDate.ToUniversalTime();
        question.UpdatedDate = question.UpdatedDate.ToUniversalTime();

        if (question.Answers != null)
        {
            foreach (var answer in question.Answers)
            {
                answer.CreatedDate = answer.CreatedDate.ToUniversalTime();
                answer.UpdatedDate = answer.UpdatedDate.ToUniversalTime();
            }
        }

        context.Questions.Add(question);
    }
}

在調用此 function 的行下方,我調用 SaveChangesAsync 方法來保存內容。

這是上面function正在讀取的種子數據。

[
    {
        "UserId": "f52f463f-7eaf-4a71-a31b-7bcc16a0a956",
        "Text": "Example question",
        "CreateDate": "2021-01-01",
        "UpdatedDate": "2021-01-01",
        "Answers": [
            {
                "UserId": "35BB2533-36F4-4CFF-9286-598291A2AF44",
                "CreatedDate": "2021-01-01",
                "UpdateDate": "2021-01-01",
                "Text": "Example answer"
            }
        ]
    }
]

我在終端中遇到異常,我可以看到 User 表中不存在的 UserId 字段似乎存在問題。 我希望我的代碼在 Answer 表中創建一個條目,並將 UserId 外鍵設置為我提供的 UUID。 你能解釋一下為什么我做錯了,以及如何正確地播種這些數據嗎?

請注意,我對 ASP.NET 完全陌生。

fail: Envy.API.Program[0]
      An error occurred during migration.
      Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
       ---> Npgsql.PostgresException (0x80004005): 23503: insert or update on table "Answer" violates foreign key constraint "FK_Answer_Users_UserId"

      DETAIL: Key (UserId)=(00000000-0000-0000-0000-000000000000) is not present in table "Users".
         at Npgsql.Internal.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|213_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
         at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
         at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
         at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
         at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
        Exception data:
          Severity: ERROR
          SqlState: 23503
          MessageText: insert or update on table "Answer" violates foreign key constraint "FK_Answer_Users_UserId"
          Detail: Key (UserId)=(00000000-0000-0000-0000-000000000000) is not present in table "Users".
          SchemaName: public
          TableName: Answer
          ConstraintName: FK_Answer_Users_UserId
          File: ri_triggers.c
          Line: 2528
          Routine: ri_ReportViolation

通過將 UserId 屬性添加到我的 Answer model 解決了該問題。 在提出問題之前我曾嘗試過此操作,但未能使其正常工作,但在我第二次嘗試時,它似乎按預期工作,所以我在第一次嘗試時一定有錯字。 謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM