nam
nam

Reputation: 23769

Defining Foreign Key in Entity Framework Code First

In the following Model example (taken from this official ASP.NET site) I understand they are defining a Foreign Key relationship between Blogs (parent) and Posts (Child) tables. But in the Blog class below what is the use of public List<Post> Posts { get; set; } property? If I remove this property and generate SQL Server database out of this Model, I can still see database was successfully created with BlogId in Posts table as Foreign Key to Blog table

namespace EFGetStarted.AspNetCore.NewDb.Models
{
    public class BloggingContext : DbContext
    {
        public BloggingContext(DbContextOptions<BloggingContext> options)
            : base(options)
        { }

        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    }

    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; }
    }
}

Upvotes: 1

Views: 308

Answers (1)

Vivien Chevallier
Vivien Chevallier

Reputation: 1522

Nam,

The Posts property in the Blog class could be useful if you have the need to access the posts directly from an instance of a Blog object.

Loading the posts could be done via lazy loading or Entity Framework Eager loading using the Include method:

    var blogs1 = context.Blogs 
                      .Include(b => b.Posts) 
                      .ToList(); 

If you remove it will not prevent the database to be properly created.

Upvotes: 3

Related Questions