多对多 - 从表中获取适当的记录 - EF LINQ

时间:2014-09-23 08:31:21

标签: entity-framework asp.net-mvc-4 linq-to-entities

我有两张关系多对多的表格。让我们说A和B表。
我还有List<List<int>> TagIdList个带有B表元素的ID 如何查找表A中包含所有TagIdList[i]元素的每个元素?我只需要表A中的ID,因此它不必是表中的所有TASKS行。

示例:

A:任务:
id:1,2,3,4,5,6

B:TAGS:
id:1,2,3,4

A-B链接:
1-2; 1-3; 2-1; 2-2; 5-3; 5-4; 6-1; 6-6;

List<List<int>> TagIdList  //(ids from TAGS)   
TagIdList[0]= {2,3}   
TagIdList[1]= {1}   
TagIdList[2]= {2,6}

结果:(来自TASKS的ids)

i=0; -> 1  
i=1; -> 2,6  
i=2; -> null

我试过了:

List<int> tags = model.TagIdList[i].IdList; //I've got it from my View
List<TASKS> tasks = myEntity.TASKS.Where(t => t.TAGS == tags).ToList();

我无法获取任务,因为出现了错误:无法创建类型的常量值。在此上下文中仅支持基本类型。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您的问题出在此处:myEntity.TASKS.Where(t => t.TAGS == tags)

如果我理解正确的问题,你需要这样的事情:

两个int列表的比较方法(取自here

public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2) {
  var cnt = new Dictionary<T, int>();
  foreach (T s in list1) {
    if (cnt.ContainsKey(s)) {
      cnt[s]++;
    } else {
      cnt.Add(s, 1);
    }
  }
  foreach (T s in list2) {
    if (cnt.ContainsKey(s)) {
      cnt[s]--;
    } else {
      return false;
    }
  }
  return cnt.Values.All(c => c == 0);
}

在linq表达式中使用此方法:

myEntity.TASKS.AsEnumerable().Where(t => ScrambledEquals<int>(t.TAGS.Select(tag=>tag.id).ToList(),tags))

答案 1 :(得分:0)

我找到了解决方案。它可能并不理想,但有效。

List<int> tags = model.TagIdList[i].IdList;

List<List<int>> whole_list = new List<List<int>>();

foreach (var t in tags) //I'm looking for every tasks' ids in every given tag
{   
    var temp = myEntity.TAGS.Find(t).TASKS.Select(task => task.Id).ToList();
    whole_list.Add(temp);
}

//now I want first list from whole_list to compare with the other lists
List<int> collection = whole_list[0]; //collection it's tasks
whole_list.Remove(collection);

//I'm taking a part which is common to all lists from whole_list
foreach (List<int> k in whole_list)
{   
    var temp = collection.Intersect(k);
    collection = temp.ToList();
}

//the collection is now what I wanted for TagIdList[i] - every task which has every tags from TagIdList[i].IdList