Blog Stats
  • Posts - 65
  • Articles - 0
  • Comments - 7
  • Trackbacks - 0

 

Wednesday, January 2, 2013

MVC ModelState.IsValid Fails When Reserved Word Used for Table Name


When a table name uses a reserved word: for example, “Action,” model validation will fail even though the model is valid. The error message from ModelState is:

“The parameter conversion from type 'System.String' to… …type failed because no type converter can convert between these types.”

For example, if a table named Action has a related table, Action_Details, where an Action may have one to many Action_Conditions, you may have a model class for Action_Details that looks like this:

    public class Action_Details
    {
        public int ID { get; set; }
        public int Action_ID { get; set; }
        public string Value { get; set; }
        public string ParentField { get; set; }
        public string ChildField { get; set; }
        public Nullable<bool> Inherit { get; set; }
        public virtual Action Action { get; set; } 
    }

My solution was to change the related table class

    public class Action_Details
    {
        public int ID { get; set; }
        public int Action_ID { get; set; }
        public string Value { get; set; }
        public string ParentField { get; set; }
        public string ChildField { get; set; }
        public Nullable<bool> Inherit { get; set; }
        //public virtual Action Action { get; set; } 
        // ** as "Action" is a reserved word, I had to use the 
        // ** fully qualified class name (i.e. UI.Models.Action) 
        // ** AND change the object name from Action to Action1
        public virtual UI.Models.Action Action1 { get; set; }
    }
 

 

Copyright © Bob Hardister