实体框架:如何从具有复合键的表中返回一行? [英] Entity framework: How to return a row from a table with composite keys?

查看:56
本文介绍了实体框架:如何从具有复合键的表中返回一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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);

推荐答案

我认为您正在寻找

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);

这篇关于实体框架:如何从具有复合键的表中返回一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆