views:

45

answers:

1

I have about 10 calls that have the same select statement. It's more than a simple FirstOrDefault, it has some db logic inside of it. I have not seen a good way to extract this into its own method or statement. I have come close with something like this:

static readonly Expression<Func<DbUser, User>> GetUser = (g) => new User {
    Uid = g.uid,
    FirstName = g.first_name,
    LastName = g.last_name,
    BigPicUrl = g.pic_big,
    Birthday = g.birthday,
    SmallPicUrl = g.pic_small,
    SquarePicUrl = g.pic_square,
    Locale = g.locale.Trim(),
    //IsFavorite = g.FavoriteFriends1.Any(x=>x.uid==uid),
    FavoriteFriendCount = g.FavoriteFriends.Count,
    LastWishlistUpdate = g.WishListItems.OrderByDescending( x=>x.added ).FirstOrDefault().added
};

The problem with this method is that I can't pass in extra parameters, like the one you see IsFavorite. I need to be able to do this type of thing while still being able to use variables to build my query statements.

A: 

Easy. Make a function:

static readonly Expression<Func<DbUser, User>> GetUser(int uid)
{ 
    return (g) => new User 
                  {
                      Uid = g.uid,
                      FirstName = g.first_name,
                      LastName = g.last_name,
                      BigPicUrl = g.pic_big,
                      Birthday = g.birthday,
                      SmallPicUrl = g.pic_small,
                      SquarePicUrl = g.pic_square,
                      Locale = g.locale.Trim(),
                      IsFavorite = g.FavoriteFriends1.Any(x=>x.uid==uid),
                      FavoriteFriendCount = g.FavoriteFriends.Count,
                      LastWishlistUpdate = g.WishListItems
                                            .OrderByDescending(x=>x.added)
                                            .FirstOrDefault().added
                  };
}
Craig Stuntz
thank you thank you
wcpro