jonathanm
Explore posts from servers❔ 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
User.cs
Post.cs
I have tried to put the Post inside of .OwnsMany, but that didn't work. How can I fix this?
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var newUser = new User
{
Id = "1",
UserName = "JohnDoe",
Email = "[email protected]"
};
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",
Email = "[email protected]"
};
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);
}
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();
}
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();
}
28 replies