【问题标题】:Using entity framework code first in MVC 3在 MVC 3 中首先使用实体​​框架代码
【发布时间】:2012-05-03 03:24:24
【问题描述】:

我对此很陌生,我真的很想帮助解决这个问题:

首先我已经有一个数据库,假设我在这个数据库中有 3 个表:User、UserMapping、UserRole。 我生成了一个具有 3 类的模型,如下所示:

public  class user
{
        public int UserID { get; set; }
        public string UserName { get; set; }

        public virtual ICollection<UserMapping> UserMappings { get; set; }
}

   public class UserMapping
    {
        public int UserMappingID { get; set; }
        public int UserID { get; set; }
        public int UserRoleID { get; set; }

        public virtual User User { get; set; }
        public virtual UserRole UserRole { get; set; }

    }

  public class UserRole
    {
        public int UserRoleID { get; set; }
        public string RoleName { get; set; }

        public virtual ICollection<UserMapping> UserMappings { get; set; }

    }

我想创建一个新用户,并为新用户添加一个用户角色。用户和用户角色没有直接关系。我想创建一个视图来创建一个新用户,使用具有强类型的用户模型类。如何在此视图中为用户创建用户角色?

请帮助...!非常感谢您。

【问题讨论】:

  • Learn the basics first,复数形式。
  • 你不需要 UserMapping 类,它可以从 User 和 UserRole 之间的关系中推断出来。用户具有角色集合,角色具有用户集合。 Entity Framework 会自动创建支持表(你称之为 UserMapping)。

标签: asp.net-mvc asp.net-mvc-3 entity-framework code-first


【解决方案1】:

您不需要自己创建 UserMapping 实体。因为当您指定 User 和 UserRole 之间的多对多关系时,EF 会自动为您创建关系表 UserUserRole 关系表。

  public  class User
     {
        public int UserID { get; set; }
        public string UserName { get; set; }

        public virtual ICollection<UserRole> UserRoles{ get; set; }
     }


  public class UserRole
    {
        public int UserRoleID { get; set; }
        public string RoleName { get; set; }

        public virtual ICollection<User> Users { get; set; }

    }

然后可以将关系表映射到已有的,

protected override void OnModelCreating(ModelBuilder modelBuilder)
{

modelBuilder.Entity<User>().HasMany(u => u.UserRoles)
            .WithMany(r => r.Users )
            .Map(m =>
            {
                m.MapLeftKey("UserID");
                m.MapRightKey("UserRoleID");
                m.ToTable("YourExistinegTableName");
            });

}

【讨论】:

  • 首先,非常感谢您的帮助!我正在使用现有的数据库。该数据库也用于其他项目,我无法更改数据库。我尝试了您的方法并且没有使用数据映射并收到错误消息,指出所需的属性“用户映射”不存在。你知道另一种方法吗?再次感谢。
  • 您可以将关系表映射到现有的。看到我已经添加了代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多