[英]How do I join 2 dbSets in a repository relationship request using Linq / Entity framework
Let's say I have the following code: 假设我有以下代码:
public ActionResult ListByJames(int jamesID, int page = 1, string sort = "Name", bool desc = false)
{
IEnumerable<Bob> orderedBobs = bobRepository.SortByColumnName(sort, desc);
IEnumerable<Bob_JamesRelationship> bobRelations = bobRelationshipRepository.Relationships;
James james = jamesRepository.GetByID(jamesID);
// At the moment, the following returning model just returns a
// list of Bobs, but I need to return a list of bobs that are
// related to the James that is passed through
ListViewModel<Bob> model = new ListViewModel<Bob>
{
Items = orderedBobs
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = orderedBobs.Count(),
Sort = sort,
Desc = desc
}
};
return View("_List", model);
}
I need to make a SQL statement like this: 我需要这样一条SQL语句:
SELECT
*
FROM
James j
JOIN
Bob_JamesRelationships r ON
j.Id = r.JamesID
JOIN
Bobs b ON
b.Id = r.BobID
but in the style of my C# code using Linq 但是使用Linq的C#代码风格
Note that the following lines 请注意以下几行
IEnumerable<Bob> orderedBobs = bobRepository.SortByColumnName(sort, desc);
IEnumerable<Bob_JamesRelationship> bobRelations = bobRelationshipRepository.Relationships;
James james = jamesRepository.GetByID(jamesID);
contain all of the information required to get the required set of Bobs back. 包含获取所需鲍勃集所需的所有信息。
A James is related to a Bob via a Bob_JamesRelationship... I also have 3 SQL tables that represent these too. 一个James通过Bob_JamesRelationship与Bob关联...我也有3个SQL表也代表了这些。
How do I go about doing this? 我该怎么做呢?
All collections must be IQueryable
if you want them to be combined into one query. 如果要将所有集合合并到一个查询中,则所有集合必须是
IQueryable
。 IEnumerable
is always an in-memory object that has no connection to a query provider. IEnumerable
始终是与查询提供程序没有连接的内存对象。 IQueryable
has an expression tree that its query provider can translate into the query language of the underlying data store. IQueryable
具有一个表达式树,其查询提供程序可以将其转换为基础数据存储区的查询语言。 Expression trees from different IQueryable
instances with the same provider can be combined into one by compose methods like Join
. 来自具有相同提供者的不同
IQueryable
实例的表达式树可以通过Join
方法之类的方法合并为一个。
So the first thing to do is return IQueryable<T>
from your repositories. 因此,第一件事是从您的存储库返回
IQueryable<T>
。 Second, make sure they share the same context instance. 其次,确保它们共享相同的上下文实例。 Then you can do things like
然后你可以做类似的事情
from bo in orderedBobs
join br in bobRelations on bo.Id equals br.BobId
join j in James on br.JamesId equals j.Id
where j.Id == jamesId
select new { bo, br, j }
and see it translated into one SQL statement. 并将其翻译成一条SQL语句。 I can't judge whether this is a small step or a giant leap for your current architecture, but it's the way to go anyhow.
我无法判断这对您当前的体系结构而言是小小的进步还是巨大的飞跃,但是无论如何,这都是前进的道路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.