0

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:

  1. 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.
  2. 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.

Neilski
  • 4,385
  • 5
  • 41
  • 74
  • I think you must add .WithMany(t => t.Comments) and .HasForeignKey(t => t.userId) as well with the same logic you did it for post – Mahmoud Sep 03 '15 at 11:50
  • I don't think that works because the User entity does not know anything about Comments (i.e. it is a unilateral relationship) the User object returned from HasOptional(t => t.User) does not have a Comments collection to reference. – Neilski Sep 03 '15 at 12:38
  • Since the BlogComment.UserId is nullable and the User record does not know about BlogComments, I thinks that maybe all I need is: HasOptional(t => t.User).WithOptionalDependent(); Can anyone tell me if this is correct? – Neilski Sep 09 '15 at 08:29

0 Answers0