MVC ASP.net创建通用帮助器

时间:2015-10-08 18:55:36

标签: c# asp.net-mvc generics helper

我有两个视图模型PublishedSongRadioStation,我希望它们具有IncrementViews(int id)功能。

我没有将函数复制并粘贴到两个控制器中,而是想制作一个通用的帮助类。

助手:

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<T>.GetElements(db, this.GetType()).Single(x => x.Id == id);

<T>无效。我是泛型的新手,我认为它期望上课,但因为课程可能是PublishedSongRadioStation我不知道该怎么做。

0 个答案:

没有答案
相关问题