我需要能够分离我的EF选择语句

时间:2010-09-22 02:16:11

标签: c# .net linq entity-framework linq-to-entities

我有大约10个具有相同select语句的调用。它不仅仅是一个简单的FirstOrDefault,它内部有一些db逻辑。我还没有看到将其提取到自己的方法或语句中的好方法。我接近这样的事情:

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
};

这种方法的问题在于我无法传递额外的参数,比如你看到的IsFavorite。我需要能够做这种类型的事情,同时仍然能够使用变量来构建我的查询语句。

1 个答案:

答案 0 :(得分:0)

易。做一个功能:

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
                  };
}