Entity Framework 关键问题

Entity Framework Key Issues

我尝试登录时遇到以下错误:

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.

我正在尝试在我的 dbcontext 中使用复合键

  // Primary Key
  this.HasKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId });

但它似乎无法拾取它,看起来它正在模型中而不是上下文中搜索键,因为当我在模型中添加“[Key]”关键字时它抱怨必须对组合键使用 HasKey

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; }
}

我该如何克服这个问题?我是否要在模型中添加 HasKey?如果是,如何添加以及为什么它没有在上下文中提取它?

如文档中所述,

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.

尝试修改代码如下:

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...
}

尝试在 [Key] 属性下方添加 Column Order 数据注释

[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; }

在 EF 6 中,Key 属性在应用于单个整数类型时会创建一个带有标识列的 PK 属性。复合键不会为整数 属性.

创建标识列