我的代碼是:如何首先使用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服務器管理我的數據庫中鍵的所有表。 我該如何解決這個問題?
您必須使用Id屬性或[Key]屬性爲您的EF實體指定主鍵。此外,它看起來像你正在使用ASP.NET身份,這是正確的?如果是,請注意https://stackoverflow.com/questions/28531201/entitytype-identityuserlogin-has-no-key-defined-define-the-key-for-this-entit –
不要使用'[Key] '在導航屬性上。在UserId屬性上嘗試'[Key,ForeignKey(「ApplicationUser」)]''。 –