在Generic方法中使用实体作为参数

时间:2016-03-11 11:51:32

标签: c# generics methods entity

使用MVC,当我注册时,我希望能够在单独的表(帐户和用户)中创建几个记录

我可以为每个创建设置不同的方法但是我想学习,我想我会尝试在一种方法中使用泛型。这可能是不合适,所以请指出它是否是

因此寄存器方法中包含以下代码:

sp_Account spAccount = new sp_Account();
// stripped out code assignations
Create(spAccount);
sp_User spUser = new sp_User();
// stripped out code assignations
Create(spUser);

在谷歌搜索了一段时间之后,我(正确或错误地)设置了Create方法,如下所示:

protected ActionResult Create<T>(T modelOf)
        {
          if (ModelState.IsValid)
          {
            Type t = modelOf.GetType();

            switch(t.Name)
              {
              case "sp_Account":
                 sp_Account spAccount = new sp_Account();
                 spAccount = ??????????;
                 db.sp_Account.Add(spAccount );

                 return View(spAccount);
                 break;
              case "sp_User":
                sp_User spUser = new sp_User();
                spUser = ??????????;
                db.sp_User.Add(spUser);

                return View(spUser);
                break;
              }
            db.SaveChanges();
          }

          return View(**********);
        }
  

请提出2个问题:

     
      
  1. ?????????? - 如何将通用modelOf分配给特定实体
  2.   
  3. ********** - 如何将通用modelOf作为View
  4. 的模型返回   

如果这是一个愚蠢的问题,请提前道歉。 并提前感谢那些帮助的人。

更新 我想打开这个&#34;创建&#34;我拥有的任何实体的方法。

1 个答案:

答案 0 :(得分:0)

进一步谷歌搜索后,最终成功加入所有信息以制定解决方案。

我的工作创建方法现在看起来像这样:

protected void Create<TEntity>(TEntity modelOf) where TEntity : class, new()
    {
      if (ModelState.IsValid)
      {
        db.Set<TEntity>().Add(modelOf);
        db.SaveChanges();
      }
    }