[英]Linq select Item where it is equal to ID in another table
I am not sure how possible this is but I have two tables and I want to grab a value from table 2 via the value of table 1. 我不确定这有多可能,但我有两个表,我想通过表1的值从表2中获取一个值。
Table 1 has the a Foreign Key called "rank" which is an int
. 表1有一个名为“rank”的外键,它是一个int
。 Table 2 has a value called "name" which is a string
. 表2有一个名为“name”的值,它是一个string
。 Now Table 1's "rank" correlates to Table 2's "ID". 现在表1的“等级”与表2的“ID”相关。
So when I say 所以,当我说
var result = db.Table1.Select(x => new { x.name, x.rank }).ToList(); //Bob - 2
I really want to say something like 我真的想说些什么
var result = db.Table1.Select(x => new { x.name, Table2.rank.Where(ID == x.rank) }).ToList(); //Bob - Gold
I am still new to LINQ though and I am not sure how to get rank
's string value from the other table within a query like this. 我仍然是LINQ的新手,我不知道如何在这样的查询中从其他表中获取rank
的字符串值。
EDIT 编辑
Tables I am using and their relational values. 我正在使用的表及其关系值。
User: ID (PK), s1elo (FK to PastElos), champ (FK to ChampionList), elo (FK to EloList) 用户:ID(PK),s1elo(FK到PastElos),冠军(FK到ChampionList),elo(FK到EloList)
PastElo: ID (PK), Rank PastElo:ID(PK),排名
ChampionList: ID (PK), name ChampionList:ID(PK),名称
EloList: ID (PK), Rank EloList:ID(PK),排名
Working example for Users and PastElo 用户和PastElo的工作示例
var result = db.Users.Join(db.PastEloes, x => x.s1elo, y => y.ID, (x, y) => new { y.Rank, x.name, x.other_items_in_Users }).ToList();
Note: PastElo is PastEloe's due to EF making everything plural when I synced up my DB, thus why User is also Users, I think that is referred to as the "context". 注意:PastElo是PastEloe,因为当我同步我的数据库时,EF使所有内容都复数,因此为什么用户也是用户,我认为这被称为“上下文”。
You could try something like the following: 您可以尝试以下内容:
var result = db.Table1.Join(db.Table2,
x=>x.rank,
y=>y.ID,
(x,y) => new { x.rank, y.Name }).ToList();
In the above linq query we make a Join
between the two tables, Table1
and Table2
based on the association and then we select that we want. 在上面的linq查询中,我们根据关联在Table1
和Table2
之间建立一个Join
,然后我们选择我们想要的。
Another way you could try to write this query would be the following: 您可以尝试编写此查询的另一种方法如下:
var result = (from t1 in db.Table1
join t2 in db.Table2
on t1.rank equals t2.ID
select new { t1.rank, t2.Name, }).ToList();
Another way to do this would be to include your Database relationships in your C# entities. 另一种方法是在C#实体中包含数据库关系。 You could use EntityRef here. 你可以在这里使用EntityRef。 See the following documentation: 请参阅以下文档:
https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/how-to-map-database-relationships https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/how-to-map-database-relationships
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.