Entity framework: How to return a row from a table with composite keys?

假如想象 提交于 2019-12-19 05:45:27

问题


  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 that belong to a user, I would do the following:

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

My question is what if I wanted to return a specific building from a specific user? What would be the most 'efficient' way of doing this? Is there a better way (such as a built-in function) than the following:

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

回答1:


I think you are lookding for DbSet.Find method. This method finds entity by primary key. If you have composite primary key, then pass key values in the order they defined in model:

var userBuilding = database.UserBuildings.Find(userId, buildingId);


来源:https://stackoverflow.com/questions/14781777/entity-framework-how-to-return-a-row-from-a-table-with-composite-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!