开发者

C# / LINQ - having trouble querying database with LINQ

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 ent开发者_Go百科ities.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 .First on your initial subset, consider using SelectMany to flatten your result set:

public List<A> FindAllA(string b_prop) 
{ 
    return (from b in entities.Bs 
            where b.B_prop == b_prop
            from a in b.Ayes
            select a).ToList(); 
} 

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 than IQueryable<Ayes>. SelectMany flattens this relationship out.



public class Repository {

        private ABEntities entities = new ABEntities();

        public IList<A> FindAllA(string b_prop)
        {
            return (from b in entities.Bs
                   where b.B_prop == b_prop
                   select b.Ayes).ToList();
        }
    }

I highly recommend you dont return queryables from a repository since each queryable implementation is different (linq/entities/sql/etc)


A LINQ query usually returns an iQueryable<type>. You can convert this to a list by doing:

        return (from b in entities.Bs
               where b.B_prop == b_prop
               select b.Ayes).ToList();

in your function.


You have one IQueryable and other one is there fore not matching Just return List<A> that should work

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜