简体   繁体   中英

Cannot seed data in Entity Framework Core

I'm having trouble seeding data into my Postgres database.

The first model represents a Question.

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; }
    }
}

The second represents an answer to a question.

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; }
    }
}

I've created a function in a class that runs in my Program.cs file to seed the data, and it looks like this.

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);
    }
}

Below the line that calls this function, I call the SaveChangesAsync method to save the content.

Here is the seed data that is being read by the above 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"
            }
        ]
    }
]

I get the exception in my terminal, I can see that it appears to have a problem with the UserId field not existing in the User table. I am expecting my code to create an entry in the Answer table with the UserId foreign key set to the UUID I provided. Can you explain why I'm doing this wrong and how I can correctly seed this data?

Do note, I am completely new to 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

The problem was resolved by adding a UserId property to my Answer model. I had attempted this prior to asking the question and failed to get it working, but on my second try it seems to work as expected, so I must have had a typo somewhere on my first attempt. Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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