将ASPNET MVC RC1迁移到RC2后的实体框架核心错误

时间:2016-06-19 22:48:49

标签: c# asp.net-mvc entity-framework entity-framework-core

我正在按照以下视频和帖子将我的应用从ASPNET MVC RC1迁移到RC2:

到目前为止,我设法让我的应用程序进行编译,但它在运行时中断,显示以下与实体框架相关的错误:

  

发生类型'System.InvalidOperationException'的异常   Microsoft.EntityFrameworkCore.dll但未在用户代码中处理

     

其他信息:无法从实体类型中删除密钥{Id}   Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUser   因为它是由实体类型中的外键引用的   Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>。   必须在引用之前删除或重新定义所有外键   密钥可以删除。

以下是我在上下文类中使用的代码:

public class AppContext : IdentityDbContext
{
    public DbSet<Entity1> Entities1 { get; set; }
    public DbSet<Entity2> Entities2 { get; set; }
    public DbSet<Entity3> Entities3 { get; set; }
    public DbSet<ApplicationUser> ApplicantionUsers { get; set; }

    public AppContext(DbContextOptions<AppContext> options) : base(options)
    {
        ChangeTracker.AutoDetectChangesEnabled = false;
        Database.EnsureCreated();
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("the connection string...");
        base.OnConfiguring(optionsBuilder);
    }
}

AppContext构造函数中的代码中断(第一行)。我尝试删除该行,但它在下一行中断。如果删除DbSets,代码会通过,但不会创建表。

我尝试将一个公共字符串Id属性添加到ApplicationUser类(尽管它应该从IdentityUser继承它)但是得到了相同的错误。下面是ApplicationUser类的代码:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;

namespace AppNamespace
{
    public class ApplicationUser : IdentityUser
    {
        public enum Gender { Male, Female }

        public enum UserStatus { Inactive, Active }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Passport { get; set; }

        public Gender Gender { get; set; }
        public DateTime Birthday { get; set; }
        public UserStatus Status { get; set; }
        public int ReferenceNumber { get; private set; }
        public int Referral { get; set; }
        public bool AcceptedTermsAndConditions { get; set; }

        public string Telephone { get; set; }
        public string Mobile { get; set; }

        public string AddressLine { get; set; }
        public string ZipCode { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public Country Country { get; set; }

        public ApplicationUser()
        {
        }
    }
}

谢谢你, 贡萨洛

1 个答案:

答案 0 :(得分:0)

好的,问题是当从IdentityDbContext派生时,上下文没有提供ApplicationUser。 这解决了这个问题:

public class AppContext : IdentityDbContext<ApplicationUser>
{ 
    ...
}
相关问题