Entity structure: how to return a row from a table using compound keys?

public class UserBuilding { [Key, Column(Order = 0)] public int UserId { get; set; } [Key, Column(Order = 1)] public int BuildingId { get; set; } public int BuildingLevel { get; set; } } 

If I wanted to return all the different buildings owned by the user, I would do the following:

 database.UserBuildings.Where(b => b.UserId == userId); 

My question is: what if I want to return a specific building from a specific user? What would be an β€œeffective” way to do this? Is there a better way (e.g. a built-in function) than the following:

 database.UserBuildings.Where(b => b.UserId == userId && b.BuildingId == buildingId); 
+8
return entity-framework composite-key row
source share
1 answer

I think you are looking for the DbSet.Find method. This method finds the object by primary key. If you have a composite primary key, then pass the values ​​of the keys in the order they are defined in the model:

 var userBuilding = database.UserBuildings.Find(userId, buildingId); 
+16
source share

All Articles