2017-05-28 21 views
0

我的代碼是:如何首先使用EF代碼向aspnet用戶添加外鍵?

public class UserGroupUser 
{ 
    public int UserGroupUserId { get; set; } 
    public string UserId { get; set; } 
    [Key, ForeignKey("UserId")] 
    public virtual ApplicationUser ApplicationUser { get; set; } 
} 

,當我嘗試創建一個控制器我得到這個錯誤:

EntityType 'IdentityUserLogin' had no key defined.Define the key for this entity type.

EntityType 'IdentityUserRole' had no key defined.Define the key for this entity type.

EntityType 'IdentityUserLogins' is based on 'IdentityUserLogin' that has no key defined.

EntityType: EnititySet 'IdentityUserRoles' is based on 'IdentityUserRole' that has no key defined.

但我可以看到在SQL服務器管理我的數據庫中鍵的所有表。 我該如何解決這個問題?

+0

您必須使用Id屬性或[Key]屬性爲您的EF實體指定主鍵。此外,它看起來像你正在使用ASP.NET身份,這是正確的?如果是,請注意https://stackoverflow.com/questions/28531201/entitytype-identityuserlogin-has-no-key-defined-define-the-key-for-this-entit –

+0

不要使用'[Key] '在導航屬性上。在UserId屬性上嘗試'[Key,ForeignKey(「ApplicationUser」)]''。 –

回答

0

實體需要一個主鍵。相應地更改其他模型。

public class UserGroupUser 
{ 
    [Key] 
    public int UserGroupUserId { get; set; } 
    public string UserId { get; set; } 
    [ForeignKey("UserId")] 
    public virtual ApplicationUser ApplicationUser { get; set; } 
} 
+0

感謝@Ppp尋求答案。你是對的。我的代碼中缺少[key]。但實際上這個問題是另一回事。雖然這個問題在其他帖子之前就已經解決了,但我會把它寫成另一個答案。 –

0

事實證明,EF不能識別IdentityUserLogin,IdentityRole,IdentityUserRole表中的鍵(我不知道原因)。所以我只好電話是那些表已經具有鍵在我MainContext類中重寫OnModelCreating方法(從System.Data.Entity.DbContext繼承):

public class MainContext : DbContext 
{ 
    public MainContext() : base("MyDatabaseConnectionString") { } 

    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 }); 
     base.OnModelCreating(modelBuilder); 
    } 

    public DbSet<UserGroup> UserGroups { get; set; } 
    public DbSet<UserGroupUser> UserGroupUsers { get; set; } 

} 

似乎這種方法生成的數據庫之前執行。

相關問題