1

DbSet 的扩展是什么?我想添加方法“FindTheLatest”。这是我的代码:这是我的代码

    公共静态列表 FindTheLatest(此 DbSet<Review> 评论,int nums)
    {
        返回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);
    }

抱歉信息不全。

4

2 回答 2

13

一方面,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();
}
于 2012-11-22T18:21:28.913 回答
3

您可以使用 Generic 实现扩展方法以接受任何类型:

public static class DbSetExtensions
{
    public static IQueryable<T> FindTheLast<T,TResult>(this IQueryable<T> t, Expression<Func<T, TResult>> expression, int nums) where T : class 
    {
      return t.OrderByDescending(expression).Take(nums);
    }
}  

并使用它:

dbContext.Entity.FindTheLast(x => x.Property,2);
于 2018-10-10T07:27:03.883 回答