Reputation: 23
I'm getting the following error when I try to login:
Project.Model.Identity.UserLogin: : EntityType 'UserLogin' has no key defined. Define the key for this EntityType. UserLogins: EntityType: EntitySet 'UserLogins' is based on type 'UserLogin' that has no keys defined.
I am trying to use a composite key in my dbcontext
// Primary Key
this.HasKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId });
But it seems to not be able to pick this up, it looks like it is searching for the key in the model and not in the context because when I added "[Key]" keyword in the model it complained about having to use HasKey for composite keys
public partial class UserLogin
{
[Key]
public string LoginProvider { get; set; }
[Key]
public string ProviderKey { get; set; }
[Key]
public string UserId { get; set; }
public virtual User User { get; set; }
}
How do I get past this? Do I add HasKey in the model and if so how, and why is it not picking it up in the context?
Upvotes: 2
Views: 361
Reputation: 143
Try adding Column Order data annotations below [Key] attribute
[Key]
[Column(Order=1)]
public string LoginProvider { get; set; }
[Key]
[Column(Order=2)]
public string ProviderKey { get; set; }
[Key]
[Column(Order=3)]
public string UserId { get; set; }
public virtual User User { get; set; }
In EF 6, the Key attribute creates a PK with an identity column when applied to a single integer type property. The composite key does not create an identity column for the integer property.
Upvotes: 3
Reputation: 2423
As described in the documentation,
When you have composite keys, Entity Framework requires you to define an order of the key properties. You can do this using the Column annotation to specify an order.
Try modifying the code to read as follows:
public partial class UserLogin
{
[Key]
[Column(Order=1)]
public string LoginProvider {get; set;}
[Key]
[Column(Order=2)]
public string ProviderKey {get; set; }
// and so on...
}
Upvotes: 5