C# MVC ASP.net创建通用帮助程序
我有两个视图模型,PublishedSong和RadioStation,我希望它们具有IncrementViewsint id函数 我不想将函数复制并粘贴到两个控制器中,而是想创建一个通用帮助器类 助手:C# MVC ASP.net创建通用帮助程序,c#,asp.net-mvc,generics,helper,C#,Asp.net Mvc,Generics,Helper,我有两个视图模型,PublishedSong和RadioStation,我希望它们具有IncrementViewsint id函数 我不想将函数复制并粘贴到两个控制器中,而是想创建一个通用帮助器类 助手: public class CustomDBHelper<T> { public static IEnumerable<T> GetElements(ApplicationDbContext db, T type) { if (type.E
public class CustomDBHelper<T>
{
public static IEnumerable<T> GetElements(ApplicationDbContext db, T type)
{
if (type.Equals(typeof(SongsController)))
return (IEnumerable<T>)db.PublishedSongs;
else if (type.Equals(typeof(RadioStationsController)))
return (IEnumerable<T>)db.RadioStations;
else
throw new Exception("Controller not found, DBHelper");
}
}
控制器:
public class MusicBaseController : Controller
{
public JsonResult IncrementViews(int id)
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
db.PublishedSongs.Single(x => x.Id == id);
var element = CustomDBHelper<T>.GetElements(db, this.GetType()).Single(x => x.Id == id);
element.UniquePlayCounts++;
db.SaveChanges();
return Json(new { UniquePlayCounts = element.UniquePlayCounts }, JsonRequestBehavior.AllowGet);
}
}
}
这行代码有问题:var element=CustomDBHelper.GetElementsdb,this.GetType.Singlex=>x.Id==Id
该文件无效。我是泛型新手,我认为它需要一个类,但因为该类可以是PublishedSong或RadioStation,我不知道如何实现它。以下实现将适用于您:
public class CustomDBHelper
{
public static IEnumerable GetElements(ApplicationDbContext db, Type type)
{
if (type.Equals(typeof(SongsController)))
{
return db.PublishedSongs;
}
else if (type.Equals(typeof(RadioStationsController)))
{
return db.RadioStations;
}
else
{
throw new Exception("Controller not found, DBHelper");
}
}
}
您需要将此函数的结果强制转换为所需的类型
另一方面,类型泛型也被用来表示类型泛型。因为您将类型作为参数传递,所以不需要这样做 为什么你需要这样一个函数呢?为什么需要按类型访问属性?因为否则我必须在控制器中复制代码。我的解决方案有用吗?我无法测试它。稍后将告诉您..Singlex=>x.Id==Id错误1'System.Collections.IEnumerable'不包含'Single'的定义,并且找不到接受'System.Collections.IEnumerable'类型的第一个参数的扩展方法'Single'。是否缺少using指令或程序集引用?请尝试在文件顶部添加using System.Linq文件,没用。CustomDBHelper.GetElementsdb上仍然没有查询方法,this.GetTypePerform对所需类型的结果IEnumerable进行强制转换。