问题描述
我有一个使用ASP.Net Identity的新ASP.NET MVC 5.1项目。
似乎可靠并且很有希望,但是今天如果使用SQL,我花了将近9个小时来做简单的事情。
I have a new ASP.NET MVC 5.1 project using the ASP.Net Identity.It seems reliable and promise, but today i spend almost 9 hours to do a simple things if using SQL.
我的问题是,我无法创建表通过CodeFirst使用外键引用默认的AspNetUsers表。
My problem is, i cannot create a table via CodeFirst with foreign key reference to the default AspNetUsers table.
例如:
我创建了一个名为- Address
public class Address
{
[Key]
public string UserId { get; set; }
public string MyAddress { get; set; }
}
但是我如何创建对 AspNetUsers ?
我尝试将上面的属性替换为
I try replace the property above by
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.
我也尝试从此OnModelCreating ://stackoverflow.com/a/20106318/83952>发布
I also try override the OnModelCreating from this post
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<-> Identity)
But when i run Add-Migration, it create the IdentityUserLogin, IdentityRole, IdentityUserRole tables and it duplicate, just the prefix is different. (AspNet<->Identity)
最后我在10秒钟内通过SQL做到了,但是我只想知道为什么我不能在CodeFirst中做?
为什么为什么很难从 Microsoft 2014 New Technology 做这样的事情。
Finally i do it by SQL in 10 seconds, but i just want to know why i cannot do in CodeFirst?And why so hard to do a such things from Microsoft 2014 New Technology.
推荐答案
您可以这样做。因为有时您可能需要1-1连接
You can do like this. because sometime you may need 1-1 connection
public class AnotherTable
{
[Key]
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser User { get; set; }
}
这篇关于如何向ASP.Net MVC 5 Identity添加外键引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!