Lightswitch多对多预处理查询方法

时间:2014-11-26 08:10:11

标签: c# visual-studio many-to-many visual-studio-lightswitch

我遇到了多对多关系数据库的预处理查询问题。

DB模型如下所示:

播放器[1] --- [N] PlayerMatch [N] ----- [1]匹配

播放器可以有多个匹配匹配可以使用 PlayerMatch附加多个播放器 表。

使用preprocessquery我想只返回给定 Player.Id 的对象。

  1. 获取给定PlayerID为
  2. 的Match实例的所有元素
  3. 从PlayerMatch获取所有元素,其中PlayerMatch.Match.ID == records来自(1)并返回该PlayerMatch.Player instaces
  4. 我想到:

    partial void PlayerOponents_PreprocessQuery(int? PlayerID, ref IQueryable<Player> query)
    {
         var playerGames = from g in this.PlayerMatches
                           where g.Player.Id == PlayerID 
                           select g.Match;
         var oponents    = from m in this.PlayerMatches
                           where (from g in playerGames where m.Match.Id == g.Id select m)
                           select m.Player;
         query = oponents;
    }
    

    如何让它发挥作用?

2 个答案:

答案 0 :(得分:1)

我设法解决它。问题是Lightswitch只支持LINQ的子集。 复杂查询有一些限制。

var oponentList = new List<Player>();
var matches = (from q in this.PlayerMatches where q.Players.Id == PlayerID select q.Matches).Execute();
foreach(Match match in matches)
{
    var oponents = (from q in this.PlayerMatches where q.Matches.Id == match.Id where q.Players.Id != PlayerID select q.Players).Execute();
    foreach (Player player in oponents)
    {
        oponentList.Add(player);
    }              
}
query = oponentList.AsQueryable().Take(oponentList.Count());

答案 1 :(得分:0)

<强>更新

我的下面的代码实际上并没有正常工作......它只是返回数据库中第一个X数量的人并忽略了我手动填充的列表的实际内容。 (也许它适用于早期版本的Lightswitch;请参阅https://social.msdn.microsoft.com/Forums/vstudio/en-US/3db15a5f-aedd-4619-a0cc-d9580a9cd921/can-i-replace-iqueryablemonthlybalance-query-with-generic-list-asqueryable-in-preprocessquery?forum=lightswitch。)

这是我现在使用的代码(工作正常):

Role trainerRole = (from r in Roles where r.Name == "Trainer" select r).Single();
var trainerIds = trainerRole.PersonRoles.Select(pr => pr.Person.Id);
query = query.Where(p => trainerIds.Contains(p.Id));

非常感谢您发布答案。它帮助我找到了一个很好的解决方案,这有点简单:

partial void Trainers_PreprocessQuery(ref IQueryable<Person> query)
{
    var trainers = new List<Person>();
    Role trainerRole = (from r in Roles where r.Name == "Trainer" select r).Single();
    foreach (PersonRole pr in trainerRole.PersonRoles)
    {
        trainers.Add(pr.Person);
    }
    query = trainers.AsQueryable().Take(trainers.Count());
}