Entity Framework (Core), Unique "Composite Columns" that are not the Key

entity-framework-core

Question

I have the following class

public Building()
{
   public int Id{Get; Set;};
   public ICollection Bars{Get; Set;};
}

public Room()
{
   public int Id{Get; Set;};

   public int BuildingId{Get; Set;};
   public Building Building{Get; Set;}; 

   public string Name{Get; Set;); 
}

I would like every room within a building to have a unique name. But I can't make the Name property unique, as various buildings could have the same room name

Room Table
Id    BuildingId    Name
1     1             Kitchen   
2     2             Kitchen    //Should be allowed as different building
3     1             Kitchen    //Should not be allowed

The only solution I could think of is making a composite key between BuildingId and Name.

modelBuilder.Entity<Room>().HasKey(r=> new {r.BuildingId, r.Name});

Fetching rooms will happen a lot in the App, and it would be much simpler to keep the Key as a simple integer. Is there a way to make this a unique composite column without making it the key?

I believe i need something to do with Index's but I can find a working example of what im after.

1
0
9/26/2018 10:20:25 AM

Accepted Answer

You don't have to use a composite key for this case, instead, you can make the combination as unique. You have to use the HasIndex and IsUnique methods like below.

modelBuilder.Entity<Room>(b =>
            {
                b.HasIndex(e => new { e.BuildingId, e.Name}).IsUnique();
            });
1
9/26/2018 10:16:24 AM


Related Questions





Related

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