I have a database with two entities, A and B. A and B have a many-to-many relationship between them (there’s also an AB table too that is created automatically to realize this). A has A_prop (key) and B has B_prop (key).
I want to, given a specific B_prop, find all the A’s that have in its relationship of B’s, (call them Ayes and Bees for the respective Navigation Properties), the B with the specific B_prop.
So I have this code:
public class Repository
{
private ABEntities entities = new ABEntities();
public IQueryable<A> FindAllA(string b_prop)
{
return from b in entities.Bs
where b.B_prop == b_prop
select b.Ayes;
}
}
The return types here doesn’t match. What I would really like is to have a List of A’s, or something similar that I can work with as in the following manner:
List<A> listofa = repository.FindAllA("some string");
foreach (A a in listofa)
{
// Do my stuff here.
}
EDIT:
Thanks for the replies. This is a solution (tested) to my problem:
public List<A> FindAllA(string b_prop)
{
return (from b in entities.Bs
where b.B_prop == b_prop
select b.Ayes).First().ToList();
}
Rather than calling
.Firston your initial subset, consider usingSelectManyto flatten your result set:This way if for some reason you had multiple records that matched in your Bs table, all of the associated As would be returned rather than just the first set matching up to your first B result. The problem with your first try is that you were returning
IQueryable<EntitySet<Ayes>>rather thanIQueryable<Ayes>.SelectManyflattens this relationship out.