Note that there are some explanatory texts on larger screens.

plurals
  1. POEntityFramework throwing binding exception when casting to base type
    primarykey
    data
    text
    <p><strong>Update</strong></p> <p>Apparently this was me just being wrong. the first example does not in fact work. I worked around this by serializing the object and then de-serializing it as the base class.</p> <hr> <p>I have some inconsistent issues from Entity Framework and am hoping someone could shed some light on why.</p> <p>This works:</p> <pre><code>public class ProductViewModel : Product { // Adds some select lists for View } public ActionResult Edit(ProductViewModel model) { if (ModelState.IsValid) { // Casting model to base type, EF has no issues. var product = (Product)model; Database.Entry(product).State = EntityState.Modified; Database.SaveChanges(); } return View(model); } </code></pre> <p>However this does not work:</p> <pre><code>public class OrderSurveyViewModel : tblSurvey { // adds select lists as ProductViewModel does } public ActionResult OrderSurvey(OrderSurveyViewModel model) { if(ModelState.IsValid){ // throws exceptions var survey = (tblSurvey)model; Database.tblSurvey.Add(survey); } } </code></pre> <p>The exception thrown is:</p> <blockquote> <p>Message: Mapping and metadata information could not be found for EntityType OrderSurveyViewModel</p> </blockquote> <p>Which makes sense since you can't change an objects type, casting it just 'hides' the types not belonging to that sub-type. But what I don't understand is why the top one works but the second one doesn't? Does the same mapping check simply not happen when you do Entry State Modified?</p> <p>Is there a way to still be able to do this without having to revert to simply creating a new base type and copying all of the field data?</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.
 

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