【问题标题】:Expand the AspNetUsers by adding an extra model - code first通过添加一个额外的模型来扩展 AspNetUsers - 首先是代码
【发布时间】:2015-04-05 16:15:14
【问题描述】:

我想更新 AspNetUsers 表并添加自定义属性。 我创建了一个名为 UserModel 的新类。

namespace theNotes.Models
{
 public class UserModel 
 {
    [Required]
    [Display(Name = "Education Level")]
    public string Grade { get; set; }

    public System.DateTime CreatedDate { get; set; }
    public bool IsActive { get; set; }
    public string IPAddress { get; set; }

    public Nullable<int> TotalFilesDownloaded { get; set; }
    public Nullable<int> FilesDownloadedToday { get; set; }
    public Nullable<decimal> Money { get; set; }
 }
}

当我在 PM 中运行命令 Add-Migration UserInfo 时,使用方法 updown 为空创建了一个类。为什么不生成这个类的信息?

编辑:我正在使用 asp.net mvc 互联网应用程序,我想做的是将这些列添加到自动生成的 AspNetUsers 表中。

【问题讨论】:

  • 您是否添加了对 DBContext 的引用?
  • 你在哪里添加了这个类?在Model 文件夹中?如果是这样,您可以发布您班级的完整代码吗?

标签: asp.net asp.net-mvc entity-framework entity-framework-6


【解决方案1】:

如果你使用 Asp.net Identity,那么你应该在继承自 IdentityUser 的 ApplicationUser 或类似的类中添加新属性。

【讨论】:

  • 您始终可以创建单独的模型并与ApplicationUser 模型建立关系。添加属性不是唯一的选择。
  • 你是对的,但是扩展“开箱即用”类似乎是最快也是最简单的解决方案。
  • 我同意这一点。除非它不可扩展。
【解决方案2】:

您的代码中缺少一些项目:

  • 您需要继承 DBContext 并将其添加到您的 UserModel 类所在的代码中:

    public class UserModelContext : DbContext { public DbSet<UserModel> UserModels{ get; set; } }

  • 您需要为新的上下文 UserModelContext 运行 enable-migrations 命令

    • 运行命令后会报错

EntityType 'UserModel' 没有定义键。定义此 EntityType 的键。

所以你需要重新设计你的表并添加一个键。

  • 需要引用外键才能引用User表

【讨论】:

    【解决方案3】:

    您需要像这样定义UserModel 类:

    [Table("AspNetUsers")]
    public class UserModel : IdentityUser
    {
       [Required]
       [Display(Name = "Education Level")]
       public string Grade { get; set; }
    
       public System.DateTime CreatedDate { get; set; }
       public bool IsActive { get; set; }
       public string IPAddress { get; set; }
    
       public Nullable<int> TotalFilesDownloaded { get; set; }
       public Nullable<int> FilesDownloadedToday { get; set; }
       public Nullable<decimal> Money { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 2014-05-24
      相关资源
      最近更新 更多