title: Updating database when using View Models
body: <p>I have a question abou view models and adding information to a database.</p>
  
  <p>Let's say i have these two classes:</p>
  
  <pre><code>public class Ad {
  public int Id { get; set; }
  public int CategoryId { get; set; }
  public string Headline { get; set; }
  public string Text { get; set; }
  public int Type { get; set; }
  
  public Category Category { get; set; }
  }
  
  public class Category {
  public int CategoryId { get; set; }
  public int CategoryName { get; set; }
  
  public IColletion&lt;Ad&gt; Ads { get; set; }
  }
  
  Context class:
  public DbSet&lt;Ad&gt; Ads { get; set; }
  public DbSet&lt;Category&gt; Categories { get; set; }
  </code></pre>
  
  <p>The models are really over simpified but i just want to get a grasp of the context. Lets say i want to create a view model for the view that are suppose to add entries to the db. How do i go about adding info to the "Ads" database table from a view model. Lets say the view model looks something like:</p>
  
  <pre><code>namespace Website.Models
  {
  public class CreateViewModel
  {
      public Ad Ad { get; set; }
      public ICollection&lt;Categories&gt; Categories { get; set; }
      public Dictionary&lt;int, string&gt; AdTypes { get; set; }
  
      public CreateViewModel()
      {
          // to populate a dropdown on the "Create" page
          this.Adtypes= new Dictionary&lt;int, string&gt;
                                {
                                    {1, "For sale"},
                                    {2, "Want to buy"},
                                    {3, "Want to trade"},
                                    {4, "Have to offer"}
                                };
      }
  }
  }
  </code></pre>
  
  <p>The only thing i really need when adding to the db is the parameters in the Ad class (although i need the view model to render the dropdowns). But how do I extract this from the CreateViewModel to add to the db.</p>
  
  <p>This is my code at the moment:</p>
  
  <pre><code>    [HttpPost]
      public ActionResult Create(Ad ad)
      {
  
          if (ModelState.IsValid)
          {
              db.Ads.Add(ad);
              db.SaveChanges();
              return RedirectToAction("Index");  
          }
  
          return View(ad);
  </code></pre>
  
  <p>Since this is expecting a Ad class, how do i extract only the Ad paramaters from the view model and insert it to the db.
  Sorry, very long post and probably some serious newbie stuff. I just didn't know how to explain it better.</p>
  
  <p>I would appreciate if someone could explain about view models, or direct me to some site that does.</p>
  
  <p>/m</p>