Note that there are some explanatory texts on larger screens.

plurals
  1. POCodeFirst One to Many Viewmodel to View
    primarykey
    data
    text
    <p>using C#, VS2012, MVC4, CodeFirst</p> <p>I've read tons of posts here and elsewhere about one to many with a viewmodel but I can't quite get it.</p> <p>I have a program, AddressBook, with two tables, Name and Phone. For each name, you can have many numbers. Models below:</p> <pre><code>namespace AddressBook.Models { public class Name { public int NameID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } //ref public ICollection&lt;Phone&gt; Phones { get; set; } } } namespace AddressBook.Models { public class Phone { public int ID { get; set; } public string Number { get; set; } //ref [Required] public int NameId { get; set; } public Name Name { get; set; } } } </code></pre> <p>and my context:</p> <pre><code>public class ContactDBContext : DbContext { public DbSet&lt;Name&gt; Names { get; set; } public DbSet&lt;Phone&gt; Phones { get; set; } } </code></pre> <p>My DetailViewModel:</p> <pre><code>public class DetailViewModel { public Name ID { get; set; } public Name FirstName { get; set; } public Name LastName { get; set; } public List&lt;Phone&gt; Number { get; set; } } </code></pre> <p>Now my controller, I start to get stuck. I'm able to call the list of Phone, but I seem can't get the isolated Name record.</p> <pre><code>public ActionResult Details(int id = 0) { DetailViewModel dvm = new DetailViewModel(); dvm.FirstName = (from n in db.Names select n).Where(m =&gt; m.NameID == id).ToString(); dvm.LastName = (from n in db.Names where n.NameID == id select n).ToString(); dvm.Number = (from n in db.Phones select n).Where(m =&gt; m.NameId == id).ToList(); //tried a couple of different things return View(dvm); //Name name = db.Names.Find(id); //if (name == null) //{ // return HttpNotFound(); //} //return View(name); } </code></pre> <p>User should be able to perform CRUD on Phone table once in the Details view for selected Name record. Phone CRUD can be completed on same or different page, whichever is easier to code.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload