简体   繁体   English

如果由包括的实体订购,如何在Linq Select Distinct中订购?

[英]How can I order in Linq Select Distinct if ordered by an Included entity?

I know that in Linq I have to do the OrderBy after doing a Select - Distinct , but I'm trying to order by an Included entity property that get lost after the Select . 我知道在Linq中,我必须在执行Select - Distinct之后必须执行OrderBy ,但是我正在尝试通过在Select之后丢失的Included实体属性进行订购。

For example: 例如:

var accounts = _context.AccountUser
                       .Include(o => o.Account)
                       .Where(o => o.UserId == userId || o.Account.OwnerId == userId)
                       .OrderByDescending(o => o.LastAccessed)
                       .Select(o => o.Account)
                       .Distinct();

As I'm doing the Where by an or of two different parameters, there is a good chance to obtain duplicated results. 当我通过两个不同参数中的一个or两个来执行Where ,很有可能获得重复的结果。 That's why I'm using the Distinct . 这就是为什么我使用Distinct的原因。

The problem here is that after I do the Select , I don't have the LastAccessed property anymore because it doesn't belong to the selected entity. 这里的问题是在执行Select ,我不再拥有LastAccessed属性,因为它不属于所选实体。

I thing the structure of the AccountUser and Account can be inferred from the query itself. 我认为AccountUserAccount的结构可以从查询本身推断出来。

If you have the bi-directional navigation properties set up: 如果您设置了双向导航属性:

var accountsQuery = _context.AccountUser
  .Where(o => o.UserId == userId || o.Account.OwnerId == userId)
  .Select(o => o.Account)
  .Distinct()
  .OrderByDescending(a => a.AccountUser.LastAccessed);

When Selecting the Account you do not need .Include() Keep in mind that any related entities that you access off the Account will be lazy-loaded. 选择帐户时,不需要.Include()请记住,您从该帐户访问的所有相关实体都将被延迟加载。 I recommend using a .Select() to extract either a flattened view model or a view model hierarchy so that the SQL loads all needed fields rather than either eager-loading everything or tripping lazy-load calls. 我建议使用.Select()提取展平的视图模型或视图模型层次结构,以便SQL加载所有需要的字段,而不是急于加载所有内容或触发延迟加载。

Since LINQ doesn't implement DistinctBy and LINQ to SQL doesn't implement Distinct that takes an IEqualityComparer , you must substiture GroupBy + Select instead: 由于LINQ并未实现DistinctBy而LINQ to SQL并未实现采用IEqualityComparer Distinct ,因此您必须使用GroupBy + Select代替:

var accounts = _context.AccountUser
                       .Include(o => o.Account)
                       .Where(o => o.UserId == userId || o.Account.OwnerId == userId)
                       .GroupBy(o => o.Account).Select(og => og.First())
                       .OrderByDescending(o => o.LastAccessed)
                       .Select(o => o.Account);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM