简体   繁体   中英

Entity Framework 6 Can't find error column

I am using MVC with Entity Framework and gets following error.

The specified cast from a materialized 'System.Int64' type to the 'System.String' type is not valid.

Error is quite understandable and easy to resolve , but issue i am facing is that in my SQL query i have plenty of columns, from error details i can't see which column is having this specific issue , i have to go through all columns one by one.

string Query= "select id,claim_no,emp_id,dept_id,location_id from staff";
var ctx = new TIAEntities()
ctx.Database.SqlQuery<ORM>(Query).ToList()

I have viewed all details in watch also, but can't find column name.

Model:-

public class ORM
        {

            public Int64 id { get; set; }
            public String claim_no { get; set; }
            public Int64 emp_id { get; set; }
            public Int64 dept_id { get; set; }
            public Int64 location_id { get; set; }
    } 

You can use these solutions:

var query = from o in ctx.ORM 
            select new 
            {
                id = o.id,
                claim_no = o.claim_no,
                emp_id = o.emp_id,
                dept_id = o.dept_id,
                location_id = o.location_id
            };

or

var query = ctx.ORM.Select(o => new ORM 
            {
                id = o.id,
                claim_no = o.claim_no,
                emp_id = o.emp_id,
                dept_id = o.dept_id,
                location_id = o.location_id
            });

The query's type is:
IQueryable<> query

For find which one of this properties raise error to use this solution

  1. In ActionResult method add else for "if (ModelState.IsValid)" like this to get problems from view in postback mode and set a breakpoint in else section and after the stop in a breakpoint use immediate window to the value of errors like this errors[0].

     if (ModelState.IsValid) { ... } else { var errors = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Value, x.Value.Errors }).ToArray(); }
  2. Use this try catch to find the error of properties and hit that.

     try { var query = from o in ctx.ORM select new { id = o.id, claim_no = o.claim_no, emp_id = o.emp_id, dept_id = o.dept_id, location_id = o.location_id }; } catch (DbEntityValidationException ex) { var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage); var fullErrorMessage = string.Join("; ", errorMessages); var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM