实体框架 – 如何添加外部参考ASP.Net MVC 5身份?

我有一个新的ASP.NET MVC 5.1项目使用ASP.Net身份。
这似乎是可靠的和承诺,但今天我花了将近9个小时来做​​一个简单的事情,如果使用sql

我的问题是,我不能通过CodeFirst创建一个表,外键引用认的AspNetUsers表。

例如:
我创建了一个名为“地址”的表

public class Address
    {
        [Key]
        public string UserId { get; set; }
        public string MyAddress { get; set; }
    }

但是如何创建AspNetUsers的外键引用?

我尝试替换上面的属性

public IdentityUser MyAddress { get; set; }
// Or
public virtual IdentityUser MyAddress { get; set; }
// Or
public virtual ApplicationUser MyAddress { get; set; }

但是他们都显示错误

One or more validation errors were detected during model generation:

MiaPos.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType. 
MiaPos.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType. 
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined. 
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.

我也尝试从这个post覆盖OnModelCreating

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
    modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
    modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId,r.UserId });
}

但是当我运行Add-Migration时,它创建了IdentityUserLogin,IdentityRole,IdentityUserRole表,并且它重复,只是前缀不同。 (AspNet身份)

最后我在十秒钟内通过sql进行操作,但是我只想知道为什么我不能在CodeFirst中执行
而为什么很难从微软2014新技术做这样的事情。

解决方法

谢谢你GáborPlesz上面的评论

我找到了解决方案。

继承IdentityUser(创建AspNetUsers表)的ApplicationUser类应该创建子类(子表)的ICollection属性

例如

public virtual ICollection<Todo> Todoes { get; set; }

所以Todo类可以引用ApplicationUser

GáborPlesz表示强烈推荐看样品。

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....