My model classes are:
public class User
{
public User()
{
Polls = new List<Poll>();
}
public int Id { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
ICollection<Poll> Polls { get; set; }
}
public class Poll
{
public int Id { get; set; }
public int PositiveCount { get; set; }
public int NegativeCount { get; set; }
public String Description { get; set; }
public User User { get; set; }
}
public class PollsContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Poll> Polls { get; set; }
}
EF created a table User_Id column for Polls table. In the Create view of the Poll, I want to specify the UserId for new poll belongs too, but intellisense shows there is no access to model.UserId, there is a model.User.Id, which is not allowing me create a Poll for existing user and rather creates new User with new Id and no association is created.
<div class="editor-label">
@Html.LabelFor(model => model.User.Id)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.User.Id)
@Html.ValidationMessageFor(model => model.User.Id)
</div>
What is the right way of creating a new Poll for an existing User then ?
I think your
Poll
class should look like:If you have a column in your
Poll
tableUser_Id
, then your model should also have this column. You can then just assign aUser_Id
to aPoll
and Entity Framework will take care of the correct linking to the rightUser
object.Further, consider making your association properties (Poll.User and User.Polls) virtual in order to use the lazy loading mechanisms of Entity Framework. See this