Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC 3: Using EF generated classes as strongly-typed models
    primarykey
    data
    text
    <p>Following on from <a href="https://stackoverflow.com/questions/6404831/">this question</a>, I'm using a simple ViewModel class to test passing a strongly-typed model to a view. Whilst Darin's answer to my original question has solved the problem I had, it's now left me scratching my head as to why I can't do the same thing with an EF generated class. Here's what I have:</p> <pre><code>public ActionResult Test() { using (MyEntities db = new MyEntities()) { var model = from c in db.Categories select new CategoryViewModel { CategoryID = c.CategoryID, Name = c.Name }; return View(model.ToList()); } } </code></pre> <p>This is CategoryViewModel:</p> <pre><code>public class CategoryViewModel { public int CategoryID { get; set; } public string Name { get; set; } } </code></pre> <p>In my view I'm simply foreaching over the model. This produces the desired results. However, one of the classes that was generated for me by EF, is Category. I was initially trying to use it to build the strongly-typed model and pass that to the view instead, like so:</p> <pre><code>public ActionResult Test() { using (MyEntities db = new MyEntities()) { var model = from c in db.Categories select new Category { CategoryID = c.CategoryID, Name = c.Name }; return View(model.ToList()); } } </code></pre> <p>This was giving me the following error:</p> <p>"The entity or complex type 'MyProjectModel.Category' cannot be constructed in a LINQ to Entities query."</p> <p>So my question is, what is the difference between CategoryViewModel and Category other than Category being generated for me? What is preventing me from using Category as my model type in this scenario? I've been looking through other questions (and answers) on SO today but I've been unable to find something that discusses this. I've also seen a few other new terms mentioned in those posts (buddy classes, automappers, POCO) but it seems premature to look into what they are without understanding the foundation of my problem.</p> <p>I'd really appreciate some insight.</p>
    singulars
    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.
 

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