开发者

How to build custom PLINQO query by multiple id's?

开发者 https://www.devze.com 2023-02-19 18:20 出处:网络
Here\'s my table structure Places PlaceId PK Name ... PlaceCategorie开发者_如何学运维s CatId PK Name

Here's my table structure

Places

  • PlaceId PK
  • Name
  • ...

PlaceCategorie开发者_如何学运维s

  • CatId PK
  • Name
  • ...

PlaceCats

  • PlaceId PK
  • CatId PK

Here's my query that pulls Places based on category id (table join)

public static IQueryable<Places> ByPlaceCat(this Table<Places> table, Expression<Func<PlaceCats, bool>> predicate) {
    var db = (DataContext)table.Context;
    var innerBizBase = db.PlaceCats.Where(predicate);
    return db.Places.Join(innerBizBase, a => a.PlaceId, ab => ab.PlaceId, (a, ab) => a);
}

I use it like this:

places = Db.Places.ByPlaceCat(a => a.CatId == 5);

But I want to be able to pull based on a List<int> of category id's. Looking through the generated PLINQO code, a query that pulls by multiple PlaceId's (but not using a joined table) looks like this:

public static IQueryable<Places> ByPlaceId(this IQueryable<Places> queryable, IEnumerable<long> values)
{
    return queryable.Where(p => values.Contains(p.PlaceId));
}

How could I essentially merge those two queries, to let me pass in a List<int> of CatId's to query by? This LINQ/PLINQO query is melting my brain. Thanks in advance!


You would need to write a extension method like this:

    public static IQueryable<Places> ByPlaceCats(this Table<Places> table, IEnumerable<int> catIds)
    {
        var db = (TestDataContext)table.Context;
        var places = (from placeCat in db.PlaceCats
                      join place in db.Places on placeCat.PlaceId equals place.PlaceId
                      where catIds.Contains(placeCat.CatId)
                      select place);
        return places;
    }

Please note that the PlaceCats table could be made into a ManyToMany relationship by adding two foreign keys to the proper tables. Once this change has been made than PLINQO will automatically generate the correct code and will create a link between the two tables skipping the intermediary table. So you could get a collection of PlaceCategories associated to the current Places entity by accessing a property on the Places entity.

Please remember to contact us if you have any questions and be sure to check out the community forums located here and PLINQO forums here.

Thanks -Blake Niemyjski (CodeSmith Support)

0

精彩评论

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