jonathanm
jonathanm
Explore posts from servers
CC#
Created by jonathanm on 5/30/2023 in #help
❔ 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",
};

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);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

var newUser = new User
{
Id = "1",
UserName = "JohnDoe",
};

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();
}
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();
}
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?
28 replies