2012-11-22 43 views
0

DbSet的擴展名是什麼?我想添加方法'FindTheLatest'。這是我的代碼: 這是我的代碼DbSet的擴展名

 
    public static List FindTheLatest(this DbSet<Review> reviews, int nums) 
    { 
     return reviews.OrderByDescending(r => r.Created).Take(nums).ToList(); 
    } 

但它不工作。我必須做什麼?

,這是我的擴展類:

public static class RestaurantReviewsExtenstion 
{ 
    public static IEnumerable<Review> FindTheLatest(this IQueryable<Review> reviews, int nums) 
    { 
     return reviews.OrderByDescending(r => r.Created).Take(nums).ToList(); 
    } 

    public static Review FindById(this System.Data.Entity.DbSet<Review> reviews, int id) 
    { 
     return reviews.SingleOrDefault(s => s.ReviewId == id); 
     //return reviews.Find(item => item.Id == id); 
    } 

    public static Review FindTheBest(this List<Review> list) 
    { 
     return list.OrderByDescending(o => o.Rating).FirstOrDefault(); 
    } 
} 

這是我DBContex類:

public class OdeToFoodDb: DbContext 
{ 
    public DbSet<Restaurant> Restaurants { get; set; } 
    public DbSet<Review> Reviews { get; set; } 

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Restaurant>() 
      .HasMany(resturant => resturant.Reviews) 
      .WithRequired(review => review.Resturant); 
     base.OnModelCreating(modelBuilder); 
    } 
} 

這是我得到的錯誤:

OdeToFoodDb _db = new OdeToFoodDb(); 
    public PartialViewResult LatestReview() 
    { 
     System.Threading.Thread.Sleep(1500); 
     //this is where i get error 
     var review = _db.Reviews.FindTheLatest(1); 
     //************************************ 
     return PartialView("_Review", review); 
    } 

對不起信息不暢。

+0

「它不工作」是*永不*的什麼是錯的足夠好的描述。 –

+0

你是否得到例外?或意外的結果? –

+0

對不起, 我是新來的這個論壇,我的英文很差,很差:( –

回答

9

一件事,List是一個通用類型。對於另一個DbSet不是任何特定類型的集合 - 您可能想要DbSet<T>爲一些適當的T。也許你的意思是:

public static List<Review> FindTheLatest(this DbSet<Review> reviews, int nums) 
{ 
    return reviews.OrderByDescending(r => r.Created).Take(nums).ToList(); 
} 

或者:

public static List<Review> FindTheLatest(this DbSet reviews, int nums) 
{ 
    return reviews.Cast<Review>() 
        .OrderByDescending(r => r.Created) 
        .Take(nums) 
        .ToList(); 
} 
+0

嗨,很不幸沒有爲我工作 –

+3

@SeyedMortezaMousavi:好吧,沒有更多的信息,我看不到我怎麼能*可能*幫助更多。你是一個尋求幫助 - 這取決於你提供的所有相關信息。請閱讀http://tinyurl.com/so-hints –

+0

@SeyedMortezaMousavi喬恩的解決方案應該爲你工作 –