我有一个使用ASP.Net Identity的新ASP.NET MVC 5.1项目.这似乎是可靠和有希望的,但今天如果使用SQL,我花了将近9个小时做一些简单的事情.
我的问题是,我不能通过CodeFirst创建一个表,使用外键引用默认的AspNetUsers表.
例如:我创建了一个名为 - Address的表
public class Address
{
[Key]
public string UserId { get; set; }
public string MyAddress { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但是我如何创建AspNetUsers的外键引用?
我尝试替换上面的属性
public IdentityUser MyAddress { get; set; }
// Or
public virtual IdentityUser MyAddress { get; set; }
// Or
public virtual ApplicationUser MyAddress { get; set; }
Run Code Online (Sandbox Code Playgroud)
但他们都仍然显示错误:
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.
Run Code Online (Sandbox Code Playgroud)
我也尝试从这篇文章中覆盖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 });
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行Add-Migration时,它会创建IdentityUserLogin,IdentityRole,IdentityUserRole表并将其复制,只是前缀不同.(ASPNET < - >身份)
最后我用SQL在10秒内完成,但我只是想知道为什么我不能在CodeFirst中做到?为什么从Microsoft 2014新技术那么难以做到这样的事情.

Gre*_*olf 29
你可以这样做.因为有时你可能需要1-1连接
public class AnotherTable
{
[Key]
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser User { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Che*_*ung 25
感谢GáborPlesz的评论.
我找到了解决方案.
继承IdentityUser(创建AspNetUsers表)的ApplicationUser类应该创建子类(子表)的ICollection属性.
例如
public virtual ICollection<ToDo> ToDoes { get; set; }
Run Code Online (Sandbox Code Playgroud)
所以ToDo类可以引用 ApplicationUser
强烈推荐看看GáborPlesz所说的样本.

| 归档时间: |
|
| 查看次数: |
34894 次 |
| 最近记录: |