简体   繁体   中英

EF Core - Add unique index

I´m doing a CRUD of countries and cities and I´m trying to add a unique index to City.Name.

I already did that to Country.Name and I would like to know if it´s possible to do that to a city so that 2 cities in 2 countries can have the same Name but in 1 country there cannot be any cities with repeated names.

Country Class

public int Id { get; set; }

[Required]
public string Name { get; set; }

public ICollection<City> Cities { get; set; }

City Class

public int Id { get; set; }

[Required]
public string Name { get; set; }

When I create a city I´m using this ViewModel

CityViewModel

public int CountryId { get; set; }


public int CityId { get; set; }


[Required]
public string Name { get; set; }

OnModelCreating

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     modelBuilder.Entity<Country>().HasIndex(c => c.Name).IsUnique();

     base.OnModelCreating(modelBuilder);
}

Example

Let´s say I have 2 countries Canada and Australia and inside Canada I have 1 city named Sydney.

If I try to create or edit another country so it gets named Canada or Australia, I want it to give an error.

If I try to create or edit another city so it gets named Sydney, if the city is created in the country Australia it should not give an error but if it´s created in the country Canada it should give an error.

I hope it helps.

You will need 2 unique indices.

To prevent multiple countries to have the same name, you need a unique index in its name:

modelBuilder.Entity<Country>().HasIndex(c => c.Name ).IsUnique();

If you also want to prevent multiple cities in the same country to have the same names, assuming that you have a country id (or code) in the Cities table, you can can create an index on multiple columns:

modelBuilder.Entity<City>().HasIndex(c => new { c.Name, c.CountryId }).IsUnique();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM