Entity Framework, relation between two tables

2019-09-02 05:26发布

问题:

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 ?

回答1:

public class Poll
{
    public int Id { get; set; }
    public int PositiveCount { get; set; }
    public int NegativeCount { get; set; }
    public String Description { get; set; }
    public int UserId { get; set; }
    public User User { get; set; }
}


回答2:

I think your Poll class should look like:

public class Poll
{
    public int Id { get; set; }
    public int PositiveCount { get; set; }
    public int NegativeCount { get; set; }
    public String Description { get; set; }
    public int User_Id { get; set; }
    public User User { get; set; }

}

If you have a column in your Poll table User_Id, then your model should also have this column. You can then just assign a User_Id to a Poll and Entity Framework will take care of the correct linking to the right User 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