I have three POCO entity classes:
public class User {
public int Id { get; set; }
public string UserName { get; set; }
}
public class BlogPost {
public int Id { get; set; }
public string Text { get; set; }
public virtual ICollection<BlogComment> Comments { get; set; }
}
public class BlogComment {
public int Id { get; set; }
public int PostId { get; set;
public int? UserId { get; set; }
public string Text { get; set; }
public virtual BlogPost Post { get; set; }
public virtual User User { get; set; }
}
Couple of points to highlight:
- From the User end, it doesn't know nor care about BlogComments. The user entity may be referenced by a great many number of entities across the project. It is important to be able to reference the User from these entities, but not from the User end of the relationship.
- The BlogComment may or may not have a reference to a User, it will depend upon whether the Comment was made by an authenticated user or not.
In my Entity Framework configuration, I define the relationship between BlogPost and BlogComment from the BlogComment end:
HasRequired(t => t.Post)
.WithMany(t => t.Comments)
.HasForeignKey(t => t.PostId);
But I am struggling to understand how I construct the optional reference to the User:
HasOptional(t => t.User)
// What comes next, and why?
Any advice would be appreciated.