我的查询出了问题。 我有两个简单的课程。我们说
public class A{
public List<B> MyCollection{get; set;}
}
public class B{
public string Id;
}
//I want to do something like that
var myB = new B{Id="1"};
context.A.Where( x=> x.MyCollection.Contains(myB)).ToList();
我该如何解决这个问题?我知道我可以做类似
的事情context.A.ToList().Where...
但这不是个好主意,特别是我有几千条记录。
UPDATE! context是EntityFramework上下文和context.A表示DbSet 我仍然收到错误“LINQ to Entities无法识别方法'Boolean Contains” 我也不能用
context.A.ToList().Where(....
因为我有成千上万的记录而且效率低下
答案 0 :(得分:2)
这对我有用:
public class A
{
public List<B> MyCollection{get; set;}
}
public class B
{
public string Id;
}
void Main()
{
// this is what you're searching for
var myB = new B{Id="1"};
// here are some A objects to put in your collection
A a1 = new A();
a1.MyCollection = new List<B>();
A a2 = new A();
a2.MyCollection = new List<B> { myB };
A a3 = new A();
a3.MyCollection = new List<B> { new B {Id="1"}};
// here's a List that represents your context.A
List<A> contextA = new List<A> {a1, a2, a3};
// here's your actual search. results has a count of 1
var results = contextA.Where( x=> x.MyCollection.Contains(myB));
Console.WriteLine(results.Count());
}
请注意,这只会找到a2,因为你确实将对象“myB”放在那里。它找不到a3,它是使用相同id创建的新对象。
如果你想找到a2和a3,你可能想要改变这样的地方:
var results = contextA.Where( x=> x.MyCollection.Any(b => b.Id == myB.Id));
答案 1 :(得分:1)
var ans = from b in context.A.MyCollection
where b.Id == 1
select b;
或
var ans = context.A.MyCollection.Where(b => b.Id == 1);
答案 2 :(得分:0)
context.A.MyCollection.Where( x= > x.Id == myB.Id).ToList();