【问题标题】:Entity Framework, relation between two tables实体框架,两个表之间的关系
【发布时间】:2011-12-11 20:47:21
【问题描述】:

我的模型类是:

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 为 Polls 表创建了一个表 User_Id 列。 在投票的创建视图中,我也想指定新投票所属的 UserId,但智能感知显示无法访问 model.UserId,有一个 model.User.Id,这不允许我创建投票现有用户,而是使用新 ID 创建新用户,并且不创建关联。

<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>

那么为现有用户创建新投票的正确方法是什么?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 entity-framework razor


    【解决方案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】:

      我认为你的 Poll 类应该是这样的:

      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; }
      
      }
      

      如果你的PollUser_Id 中有一个列,那么你的模型也应该有这个列。然后,您只需将 User_Id 分配给 Poll,Entity Framework 将负责正确链接到正确的 User 对象。

      此外,考虑使您的关联属性(Poll.User 和 User.Polls)虚拟化,以便使用 Entity Framework 的延迟加载机制。 见this

      【讨论】:

      • 我会尝试你的建议。我只是感到困惑,因为 User_Id 列实际上是存在的,并且模型不提供对它的访问权限。你知道为什么吗?
      • 尝试了您的建议,现在 EF 创建了没有任何关联的 User_Id 列,并将 User_Id1 作为用户表的 FK。
      • 您使用的是什么版本的 EF?先编码还是带有 edmx 映射文件的“普通”文件(我不知道它的名称)?
      • @Chuchelo:使用UserId 作为Poll 实体中的FK 属性的名称,然后再试一次。
      • @Ladislav Mrnka,现在 EF 创建了 UserId_Id 列,结果是一样的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多