I have a model:
User
public class User {
public int Id { get; set; }
public string UserName {get; set;}
...
public int? ManagerId {get; set;}
public User Manager {get; set;}
public int? SupervisorId {get; set;}
public User Supervisor {get; set;}
..
}
I have checked my MySQL Db, and found that ManagerId is unique. I didn't set it as unique. Now i want to remove that using dotnet ef migrations. How to do that ?
I use donet core 2.1 at the moment.
I have test with remove the ManagerID and Manager and do dotnet ef migrations add UpdateUser
checked and ManagerID is removed. then I tried to add again new name AssignedManagerID and it created new one with unique is true.
migrationBuilder.CreateIndex(
name: "IX_Users_AssignedManagerId",
table: "Users",
column: "AssignedManagerId",
unique: true);
my Datacontext: public DbSet Users {get; set;}
I have no Fluent at all on OnModelCreating() for User
EF Core is confused by the two self referencing User
navigation properties and wrongly decides that you are trying to model one-to-one relationship between User.Manager
and User.Supervisor
. It (randomly) selects the Suprevisor
as principal and creates unique FK relationship through ManagerId
. SuprevisorId
is not treated as FK, hence no FK relationship is created for it.
As usual when EF Core assumptions are incorrect, you should resolve them explicitly with data annotations and/or fluent API. For self referencing relationships the only option is fluent API, so add the following to your OnModelCreating
override to create two one-to-many relationships:
modelBuilder.Entity<User>().HasOne(e => e.Manager).WithMany();
modelBuilder.Entity<User>().HasOne(e => e.Supervisor).WithMany();
you can try below code.
migrationBuilder.DropIndex(name:"IX_Users_AssignedManagerId",table:"Users");
Its working in my project. thanks