Entity Framework, relation between two tables

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-07 05:35:09

问题


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



来源:https://stackoverflow.com/questions/8467338/entity-framework-relation-between-two-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!