简体   繁体   中英

Use of an entity as a parameter in a Generic method

Using MVC, when I register, I want to be able to create a couple of records in seperate tables (an account and a user)

I could set up different methods for each create but as I like to learn, I thought I'd try to use Generics in just one method. This may or not be appropriate so please point out if it isn't.

So the register method has in it the following code:

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

And after Googling for a while, I have (rightly or wrongly) set the Create method as follows:

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 questions please:

  1. ?????????? - How do I assign the generic modelOf to a particular entity
  2. ********** - How do I return the generic modelOf as a model for the View

New to this so apologies in advance if this is a stupid question. And thanks in advance for those who help.

UPDATE I would like to open up this "Create" method to ANY entity I have.

After further Googling finally managed to join all the info to work out a solution.

My working Create method now looks like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM