So I am working on some Entity Framework Code First. I am pretty new at database relational mapping in general. I have created a generic example for my question which I will post the code for below.
The scenario is a simple poll on a forum. A user can vote on a poll by selecting an option (or perhaps multiple poll options).
Poll and Option have a one-to-many relationship.
Option and User have a many-to-many relationship.
Poll and User have a many-to-many relationship.
But the Users that Poll has will basically be compiled from the Users that Options has, since to vote on an option, you must vote on the poll and vice-versa. So basically I guess it could be described as a User/Options join table with the Options’ Polls’ primary keys tacked on. Or it could be kind of like a User/Poll join table with Option as an array of complex types or something.
Anyways I have been working with the Fluent API (DbModelBuilder), but I have yet to get something like what I am looking for. Help?
Poll.cs
public class Poll
{
public long ID { get; private set; }
public ICollection<Option> Options { get; set; }
public ICollection<User> Users { get; set; }
}
Option.cs
public class Option
{
public long ID { get; private set; }
public long PollID { get; set; }
public ICollection<User> Users { get; set; }
}
User.cs
public class User {
public long ID { get; private set; }
public ICollection<Option> Polls { get; set; }
public ICollection<User> Options { get; set; }
{
Why do you need connection between
PollandUser? That is redundant information – you can always get that data by query throughOptions. If you really want it introduce forth entity calledVotewhich will keepPollId,UserIdandOptionId. Your application logic will have to ensure that valid combination ofOptionIdandPollIdare used. Another way to solve this is creating composite key inOptionconsisting fromOptionIdandPollId. Then you will create many to many relation betweenUserandOption. It will partially solve needs fro Poll dependency in user and it will completely remove problems with checking valid pairs ofOptionIdandPollId.