How to remove unique index from Dotnet EF?

.net c# ef-core-2.1 entity-framework-core


I have a model:


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.

                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

9/12/2018 9:51:18 AM

Accepted Answer

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();
9/12/2018 9:50:59 AM

Popular Answer

you can try below code.


Its working in my project. thanks

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow