c# - 使用 ApplicationUser 时创建数据库时 MVC5 Entity Framework 代码优先错误

标签 c# entity-framework asp.net-mvc-5 code-first asp.net-identity

非常感谢有关如何在 MVC5 中我自己的自定义类中使用 ApplicationUser 的一些指导。

简单模型,使用脚手架创建 Controller 和 View ,sm DbContext 为来自 Internet 应用程序模板的默认 ApplicationUser (IdentityUser)。我想使用 ApplicationUser 用当时登录者的详细信息来标记事务。

当 Entity Framework 尝试 DropAndRecreateAlways 时,我收到两个数据库错误之一

首先是我的课:

public class Example
{
    public int ID { get; set; }

    [Required]
    public string Description { get; set; }

    [Required]
    public double Amount { get; set; }

    [Required]
    public virtual ApplicationUser CreatedBy {get; set;}

    [Required]
    public virtual ApplicationUser ModifiedBy { get; set; }
}

Entity Framework 尝试创建数据库时遇到的错误是:

  1. {“在模型生成过程中检测到一个或多个验证错误:\r\n\r\nMvcApplication1.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' 未定义 key 。为此 EntityType 定义 key 。\r\nMvcApplication1.Models.IdentityUserRole: : EntityType 'IdentityUserRole' 未定义键。请为此 EntityType 定义键。\r\nIdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' 基于未定义键的类型 'IdentityUserLogin'。\r\nIdentityUserRoles:EntityType:EntitySet“IdentityUserRoles”基于未定义键的类型“IdentityUserRole”。\r\n"}

  2. 删除时级联带来的引用完整性(我可以重写 DbContext 以删除级联删除)

实现这一目标的最佳方法是什么?任何指导将不胜感激。

最佳答案

您的问题是您忘记打电话

base.OnModelCreating(modelBuilder);

最重要的是,就像您所说的那样,ApplicationDbContext 是默认创建的,继承自 IdentityDbContext。所以调用base.OnModelCreating,让你的基类即IdentityDbContext,生成你需要的一切。

但是如果您仍然想使用流畅的 API,为这两个实体创建 key 的正确方法是

modelBuilder.Entity<IdentityUserLogin>().HasKey(t => new { t.UserId, t.ProviderKey, t.LoginProvider });
modelBuilder.Entity<IdentityUserRole>().HasKey(t => new { t.RoleId, t.UserId });

如果不这样做,调用 UserManager 的 AddToRole(userid, rolename) 方法将引发异常,需要您添加额外的键,并显示消息“需要字段 UserId 或 RoleId”。

关于c# - 使用 ApplicationUser 时创建数据库时 MVC5 Entity Framework 代码优先错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24696158/

相关文章:

c# - 内存流替代品?

c# - 关闭 .NET SerialPort 后的 ObjectDisposedExecption

c# - 在多个项目中使用相同的数据库

c# - 如何使用 Entity Framework 将空值传递给存储过程?

security - MVC 5 安全措施

javascript - onchange 事件触发后表 TH 未正确显示

c# - Dispose 被 Microsoft DependencyInjection 多次调用

C# 4.0 如何获取给定字符串的 64 位哈希码

c# - 使用 Entity Framework 4 填充 DropDownList

asp.net-mvc - 无法将 App_Data 中的 .mdf/.ldf checkin TFS