C#C
C#3y ago
jonathanm

❔ Can't seed one-to-many relation efcore

Hello, I am stuck on a error while trying to seed a database with Efcore.

DataContext.cs
protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        
        var newUser = new User
        {
            Id = "1",
            UserName = "JohnDoe",
            Email = "johndoe@gmail.com"
        };

        modelBuilder.Entity<User>().HasData(newUser);

        var newPost = new Post
        {
            Id = "1",
            Content = "Hello World!",
            CreatedAt = DateTime.Now,
            UpdatedAt = DateTime.Now,
            UserId = newUser.Id,
            User = newUser
        };
        
        modelBuilder.Entity<Post>().HasData(newPost);
    }


User.cs
public class  User : IdentityUser
{
    public Uri? ProfilePicture { get; set; }
    public List<Post> Posts { get; set; } = new();
}


Post.cs
using System.ComponentModel.DataAnnotations;

namespace Tweeter.Shared.Models;

public class Post
{
    public String Id { get; set; }
    [Required, MaxLength(280)]
    public string Content { get; set; } = "";
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }
    public string UserId { get; set; } = "";
    public User User { get; set; } = new();
}


I have tried to put the Post inside of .OwnsMany, but that didn't work. How can I fix this?
Was this page helpful?