【问题标题】:How do I add a foreign key to aspnet user using EF code first?如何首先使用 EF 代码向 aspnet 用户添加外键?
【发布时间】:2017-05-28 08:06:59
【问题描述】:

我的代码是:

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

当我尝试创建控制器时出现此错误:

EntityType 'IdentityUserLogin' 没有定义键。定义键 此实体类型。

EntityType 'IdentityUserRole' 没有定义键。定义键 此实体类型。

EntityType 'IdentityUserLogins' 基于 'IdentityUserLogin' 没有定义键。

EntityType: EnititySet 'IdentityUserRoles' 基于 没有定义键的“IdentityUserRole”。

但是我可以在我的数据库中的所有表的 SQL 服务器管理中看到键。 我该如何解决这个问题?

【问题讨论】:

  • 您必须使用Id 属性或[Key] 属性为您的EF 实体指定主键。看起来您正在使用 ASP.NET Identity,对吗?有的话关注stackoverflow.com/questions/28531201/…
  • 不要在导航属性上使用[Key]。在 UserId 属性上尝试[Key, ForeignKey("ApplicationUser ")]

标签: entity-framework ef-code-first


【解决方案1】:

实体需要一个主键。相应地更改您的其他模型。

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

【讨论】:

  • 感谢@Ppp 的回答。你说的对。我的代码中缺少 [key]。但实际上问题是别的。虽然这个问题之前在其他帖子中已经解决了,我还是写个答案吧。
【解决方案2】:

事实证明,EF 无法识别 IdentityUserLogin、IdentityRole、IdentityUserRole 表中的键(我也不知道原因)。所以我不得不通过在我的 MainContext 类(继承自 System.Data.Entity.DbContext)中覆盖 OnModelCreating 方法来告诉这些表已经有键:

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

}

似乎这个方法在生成数据库之前执行。

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 2023-04-04
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    相关资源
    最近更新 更多