![](/img/trans.png)
[英]Linq: IQueryable extension methods works on DBSet but not on ICollection
[英]extension for DbSet
DbSet的扩展名是什么? 我想添加方法“ FindTheLatest”。 这是我的代码:这是我的代码
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);
}
对不起,信息不好。
一方面, 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();
}
您可以使用泛型实现扩展方法以接受任何类型:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.