I'm having problem on my application with postgres. For background I am trying to implement this DB Model:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
I was properly able to create database in Postgres, connect my .Net application to the database etc. the only thing holding me back is after I save an object:
var blog = new Blog();
blog.Url = "UrlTest";
var post = new List<Post>();
var entry = new Post();
post.Title = "Entry Title";
post.Add(entry);
blog.Posts = post;
context.Blog.Add(blog);
context.SaveChanges();
Just a straight forward one to many relationship. After saving the changes, I query the context and it is able to see the relationship of the Blog and Post that I just created.
Unfortunately when I restart my .Net Core App and try to list all Blog then it will show as null but when I went to the Database Server and query Post table I am able to confirm that it still have the Blog Id.
I tried all suggestions below but nothing works on my end: Entity framework code-first null foreign key
Edit: Here is my DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>();
modelBuilder.Entity<Post>();
modelBuilder.Entity<Blog>()
.HasMany(c => c.Post)
.WithOne(c => c.Blog)
.HasForeignKey(c => c.BlogId)
.OnDelete(deleteBehavior: DeleteBehavior.Cascade);
base.OnModelCreating(modelBuilder);
}
public DbSet<Post> Posts { get; set; }
public DbSet<Blog> Blogs { get; set; }
I also tried putting virtual on List in Blog Model and Blog in Post Model but didn't work