繁体   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