OK, so in Entity Framework I have two classes along the lines of,
public class User
{
public int ID { get; set; }
public string Username { get; set; }
}
public class Post
{
public int ID { get; set; }
public string Contents { get; set; }
public virtual ICollection<User> Likes { get; set; }
}
The problem is, a User can only like one Post at a time – if I do like currPost.Likes.Add(currUser);, it removes that user from whichever post it had liked before, and makes it like this new post. Looking at the database, it turns out that EF isn’t referencing the User from the Post, instead it has a Post_ID column for each user which references a post.
How would I force EF to create an array or something of Users in my Posts table, instead of how it’s doing it now? Am I misunderstanding the point of ICollection (like, should I be using a List or Array instead?) Thanks!
What you are looking for is a many to many collection. One of the ways EF allows you to do this is with the model builder. Take a look at my post on navigation properties for an example of how to do this (In the Many Relationship section).
What this is going to do is to create a link table in the database to allow many users to like a post AND many posts to be liked by a user.
You could then express your model like this: