Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 461
Ben_jamin Avatar asked Sep 26 '18 10:09

Ben_jamin


1 Answers

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();
            });
like image 106
vivek nuna Avatar answered Nov 10 '22 21:11

vivek nuna