2010-09-22 61 views
0

我有大約10個具有相同選擇語句的調用。它不僅僅是一個簡單的FirstOrDefault,它裏面有一些數據庫邏輯。我還沒有看到將這種方法提取到自己的方法或聲明中的好方法。我已經接近像這樣的東西:我需要能夠分開我的選擇語句爲EF

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一個。我需要能夠做這種類型的事情,同時仍然能夠使用變量來構建我的查詢語句。

+0

的[這種方法不能被翻譯成表達商店]可能重複(http://stackoverflow.com/questions/3757343/this-method-cannot-be-translated-into-a -store-expression) – RPM1984 2010-09-22 02:34:43

+0

這是第2部分...我需要知道是否可以用變量做這個 – 2010-09-22 04:47:46

回答

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

謝謝謝謝 – 2010-09-22 14:29:43