【问题标题】:MVC ASP.net Creating a generic helperMVC ASP.net 创建一个通用帮助器
【发布时间】:2016-01-06 13:09:22
【问题描述】:

我有两个视图模型,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&lt;T&gt;.GetElements(db, this.GetType()).Single(x =&gt; x.Id == id);

&lt;T&gt; 无效。我是泛型新手,我认为它需要一个类,但因为该类可能是 PublishedSongRadioStation 我不知道该怎么做。

【问题讨论】:

  • 为什么还需要这样的功能呢?为什么需要按类型访问属性?
  • 因为否则我将不得不在控制器中复制代码
  • 我的解决方案有用吗?
  • 我无法在 ATM 上测试它。稍后会告诉你。

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


【解决方案1】:

以下实现将为您工作:

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");
        }
    }
}

您需要将此函数的结果转换为所需的类型。

顺便说一句,类型泛型是用来作为泛型类型的。由于您将类型作为参数传递,因此没有必要。

【讨论】:

  • .Single(x =&gt; x.Id == id) 错误 1 ​​'System.Collections.IEnumerable' 不包含 'Single' 的定义,并且没有扩展方法 'Single' 接受类型为 'System.Collections.IEnumerable' 的第一个参数可以被发现(您是否缺少 using 指令或程序集引用?)
  • 尝试在文件顶部添加“使用 System.Linq”。
  • 没用。 CustomDBHelper.GetElements(db, this.GetType())上仍然没有查询方法
  • 对生成的 IEnumerable 执行所需类型的“强制转换”。
猜你喜欢
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 2011-08-17
相关资源
最近更新 更多