title: MVC - Insert post data into database
body: <p>I'm working with MVC and have created a form to insert values into my database. </p>
  
  <p>My database structure has the relationships:</p>
  
  <ul>
  <li>One -> Many</li>
  <li>Many -> Many</li>
  </ul>
  
  <p>For Example:
  The User table contains a foreign key to the table Company. In my View, I have a dropdownlist which contains all the companies.</p>
  
  <p>What I probably need is a working example of inserting data into tables with foreign keys.
  I have searched around and tried many solutions but cannot figure out how to make it work.</p>
  
  <p>Here's my code:</p>
  
  <p><strong>Model:</strong></p>
  
  <pre><code> public class DefaultConnection : DbContext
      {
          public DefaultConnection()
              : base("DefaultConnection")
          {
          }
  
          public DbSet&lt;User&gt; users{ get; set; }
      }
  
      public class Company
      {
          public int Id { get; set; }
          public string Name{ get; set; }
      }
  public class User
      {
          public int Id { get; set; }
  
          [ForeignKey("Company")]
          public int Id_Company { get; set; }
          public Company Company{ get; set; }
      }
  </code></pre>
  
  <p><strong>ViewModel:</strong></p>
  
  <pre><code>public class MyViewModel
      {
          public MyViewModel()
          {
              this.u= new User();
              this.cl = new Companylist();  &lt;== another class which i have create a selectlist
          }
  
          public User u{ get; set; }
          public Companylist cl{get;set;}
  }
  </code></pre>
  
  <p><strong>View:</strong></p>
  
  <pre><code>&lt;ol&gt;
     &lt;li&gt;
        @Html.LabelFor(m =&gt; m.cl.Ncompany)&lt;br /&gt;
        @Html.DropDownListFor(o =&gt; o.cl.Ncompany, Model.cl.Ncompany, "-- Select --", new { @class = "abc" })
      &lt;/li&gt;
      &lt;li&gt;
        @Html.LabelFor(m =&gt; m.u.Name)&lt;br /&gt;
        &lt;input type="text" name="Name" value="" /&gt;
      &lt;/li&gt;
  &lt;/ol&gt;
  </code></pre>
  
  <p><strong>Controller:</strong></p>
  
  <pre><code> [HttpPost]
          public ActionResult Create(MyViewModel model)
          {
              if (ModelState.IsValid)
              {
                  db.users.Add(model);?????????????????
                  db.SaveChanges();
                  return RedirectToAction("Index");
              }
  
              return View(model);
          }
  </code></pre>