I have this scenario:
public class Member
{
public int MemberID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public string Message { get; set; }
public virtual ICollection<Member> Members { get; set; }
}
public class MemberComment
{
public int MemberID { get; set; }
public int CommentID { get; set; }
public int Something { get; set; }
public string SomethingElse { get; set; }
}
How do I configure my association with fluent API? Or is there a better way to create the association table?
It’s not possible to create a many-to-many relationship with a customized join table. In a many-to-many relationship EF manages the join table internally and hidden. It’s a table without an Entity class in your model. To work with such a join table with additional properties you will have to create actually two one-to-many relationships. It could look like this:
If you now want to find all comments of members with
LastName= “Smith” for example you can write a query like this:… or …
Or to create a list of members with name “Smith” (we assume there is more than one) along with their comments you can use a projection:
If you want to find all comments of a member with
MemberId= 1:Now you can also filter by the properties in your join table (which would not be possible in a many-to-many relationship), for example: Filter all comments of member 1 which have a 99 in property
Something:Because of lazy loading things might become easier. If you have a loaded
Memberyou should be able to get the comments without an explicit query:I guess that lazy loading will fetch the comments automatically behind the scenes.
Edit
Just for fun a few examples more how to add entities and relationships and how to delete them in this model:
1) Create one member and two comments of this member:
2) Add a third comment of member1:
3) Create new member and relate it to the existing comment2:
4) Create relationship between existing member2 and comment3:
5) Delete this relationship again:
6) Delete member1 and all its relationships to the comments:
This deletes the relationships in
MemberCommentstoo because the one-to-many relationships betweenMemberandMemberCommentsand betweenCommentandMemberCommentsare setup with cascading delete by convention. And this is the case becauseMemberIdandCommentIdinMemberCommentare detected as foreign key properties for theMemberandCommentnavigation properties and since the FK properties are of type non-nullableintthe relationship is required which finally causes the cascading-delete-setup. Makes sense in this model, I think.