0

as I am currently learning how Entity Framework works I got following question:

On creating a basic 1:n relationship (code-first) I did read that I should do it like this:

public class Post
{
    public int PostId { get; set; }
    [MaxLength(200)]
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

There are both reference and Id field for the book-post relationship. Is this required?

I always did the database connection manually and only had the reference field

public Blog Blog { get; set; }

This way I can access the Blog Id too and I don't have to keep both up-to-date. It seems like the EF migrations don't work this way.

Any reasons for that? Is it best-practice to keep both, reference and Id field?

johannespartin
  • 501
  • 3
  • 15
  • Should have no impact on migrations other than if you exclude the FK EF will create one for you in the database (Blog_ID). – Steve Greene May 09 '17 at 13:16

1 Answers1

1

It's not required to include the Id, however if you want to enable lazy loading by using the virtual keyword and there are instances where you only need the Id of the object it might be useful to include it seperately.

An example would be:

public virtual Blog Blog { get; set; }
public int BlogId { get; set; }

For more information about lazy/eager loading: https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx

Timmeh
  • 398
  • 2
  • 14