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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With