Search code examples
asp.net-coreentity-framework-corenpgsql

Unable to implement database model relationships


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


Solution

  • This answer is actually from Mustafa Gursel on the comments on my post - learn.microsoft.com/en-us/ef/core/querying/related-data

    I'm not sure if it is Postgres related or .net core since my experience on .Net MVC 4 with MSSQL is that i don't need to declare lazy loading aside from declaring the "virtual".

    In this case I need to install Entity Framework Proxy to make it work without doing Eager Loading.