Reputation: 453
I am migrating my app from ASPNET MVC RC1 into RC2 following the following video and post:
So far I managed to get my app to compile but it breaks on runtime showing the following error related to 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.
Below is the code I am using in the context class:
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);
}
}
The code breaks in the AppContext constructor (first line). I tried removing that line but it breaks in the next one. If I remove the DbSets the code passes through but the tables are not created.
I tried adding a public string Id property to the ApplicationUser class (despite it should inherit it from IdentityUser) but got the same error. Below is the code for the ApplicationUser class:
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()
{
}
}
}
Thank you, Gonzalo
Upvotes: 3
Views: 483
Reputation: 453
Ok, the issue was that the context was not providing the ApplicationUser when deriving from IdentityDbContext. This fixed the problem:
public class AppContext : IdentityDbContext<ApplicationUser>
{
...
}
Upvotes: 0