我正在按照以下视频和帖子将我的应用程序从 ASPNET MVC RC1 迁移到 RC2:
到目前为止,我设法让我的应用程序编译,但它在运行时中断,显示以下与 Entity Framework 相关的错误:
An exception of type
'System.InvalidOperationException'
occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user codeAdditional information: Cannot remove key {
Id
} from entity typeMicrosoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUser
because it is referenced by a foreign key in entity typeMicrosoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>
. All foreign keys must be removed or redefined before the referenced key can be removed.
下面是我在上下文类中使用的代码:
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 构造函数中中断(第一行)。我尝试删除该行,但它在下一行中断了。如果我删除 DbSet,代码会通过,但不会创建表。
我尝试向 ApplicationUser 类添加一个公共(public)字符串 Id 属性(尽管它应该从 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()
{
}
}
}
谢谢, 贡萨洛
最佳答案
好的,问题是上下文在从 IdentityDbContext 派生时没有提供 ApplicationUser。 这解决了问题:
public class AppContext : IdentityDbContext<ApplicationUser>
{
...
}
关于c# - 将 ASPNET MVC RC1 迁移到 RC2 后出现 Entity Framework Core 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37912604/