扩展DbSet [英] extension for DbSet
本文介绍了扩展DbSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是扩展DbSet?我想补充的方法FindTheLatest。这是我的code:
这是我的code
What is extension for DbSet? I want to add method 'FindTheLatest'. this is my code: this is my code
public static List FindTheLatest(this DbSet<Review> reviews, int nums)
{
return reviews.OrderByDescending(r => r.Created).Take(nums).ToList();
}
但它不工作。我必须做的?
But it doesn't work. What i must to do?
这是我的扩展类:
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类:
this is my DBContex Class:
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);
}
对不起信息不畅。
Sorry about poor information.
推荐答案
好了一件事,列表
是一个泛型类型。对于另一个 DbSet
不是一套任何的具体的的类型 - 您可能希望 DbSet&LT; T&GT;
对于一些适当的 T
。也许你的意思是:
Well for one thing, List
is a generic type. For another DbSet
isn't a set of any specific type - you probably want DbSet<T>
for some appropriate T
. Perhaps you mean:
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();
}
这篇关于扩展DbSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文