如何向 ASP.Net MVC 5 Identity 添加外键引用?

2024-04-13

我有一个使用 ASP.Net Identity 的新 ASP.NET MVC 5.1 项目。 它看起来可靠且有希望,但今天我花了近 9 个小时来做​​一些简单的事情(如果使用 SQL)。

我的问题是,我无法通过 CodeFirst 创建一个带有默认 AspNetUsers 表的外键引用的表。

例如: 我创建了一个名为 - 的表Address

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

但是我如何创建一个外键引用AspNet用户?

我尝试将上面的属性替换为

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 https://stackoverflow.com/a/20106318/83952

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

但当我跑步时添加迁移,它创建 IdentityUserLogin、IdentityRole、IdentityUserRole 表,并且它是重复的,只是前缀不同。 (AspNet身份)

最后我在 10 秒内通过 SQL 完成了它,但我只是想知道为什么我不能在 CodeFirst 中完成? 为什么做这样的事情这么难微软2014新技术.


感谢您加博尔·普莱斯对于上面的评论。

我找到了解决方案。

继承的ApplicationUser类身份用户(即创建AspNetUsers表)应该创建子类(子表)的ICollection属性。

e.g.

public virtual ICollection<ToDo> ToDoes { get; set; }

So the ToDo类可以参考应用程序用户

强烈推荐查看示例加博尔·普莱斯 said.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何向 ASP.Net MVC 5 Identity 添加外键引用? 的相关文章

随机推荐