Why Entity Framework throws invalid cast

.net c# casting entity-framework entity-framework-core

Question

No matter what method I use to query for data on I can't get past this one method. It always throws an error:

Specified cast is not valid.

Not sure why this one is going nuts on the casting. The column is defined as INT(10) in MySQL, the model is an INT on the ID attribute, the input variable is an INT, and yet there is still a cast error! Using almost the exact same logic to create, delete, and getAllCustomer methods works fine. This is the only problem one.

Here is the method in question:

public static bool UpdateCustomerById(int id, string updatedName, int updatedAddressId)
{
        try
        {
            using (Context db = new Context())
            {
                Customer customer = (Customer)db.Find(typeof(Customer),id);
                //Customer customer = db.Customer.Find(id);
                customer.AddressId = updatedAddressId;
                customer.CustomerName = updatedName;
                db.SaveChanges();
            }

            return true;
        }
        catch (Exception err)
        {
            Console.WriteLine("Error: " + err);
            throw new Exception("Couldn't update the customer because: " + err);
        }
}

Model:

using System;
using System.Collections.Generic;

namespace Scheduler.Data.Models
{
    public partial class Customer
    {
        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public int AddressId { get; set; }
        public sbyte Active { get; set; }
        public DateTime CreateDate { get; set; }
        public string CreatedBy { get; set; }
        public DateTime LastUpdate { get; set; }
        public string LastUpdateBy { get; set; }
    }
}

HTML table representation of the database table

<table border=1>
<tr>
<td bgcolor=silver class='medium'>Field</td>
<td bgcolor=silver class='medium'>Type</td>
<td bgcolor=silver class='medium'>Null</td>
<td bgcolor=silver class='medium'>Key</td>
<td bgcolor=silver class='medium'>Default</td>
<td bgcolor=silver class='medium'>Extra</td>
</tr>

<tr>
<td class='normal' valign='top'>customerId</td>
<td class='normal' valign='top'>int(10)</td>
<td class='normal' valign='top'>NO</td>
<td class='normal' valign='top'>PRI</td>
<td class='normal' valign='top'>NULL</td>
<td class='normal' valign='top'></td>
</tr>

<tr>
<td class='normal' valign='top'>customerName</td>
<td class='normal' valign='top'>varchar(45)</td>
<td class='normal' valign='top'>NO</td>
<td class='normal' valign='top'></td>
<td class='normal' valign='top'>NULL</td>
<td class='normal' valign='top'></td>
</tr>

<tr>
<td class='normal' valign='top'>addressId</td>
<td class='normal' valign='top'>int(10)</td>
<td class='normal' valign='top'>NO</td>
<td class='normal' valign='top'></td>
<td class='normal' valign='top'>NULL</td>
<td class='normal' valign='top'></td>
</tr>

<tr>
<td class='normal' valign='top'>active</td>
<td class='normal' valign='top'>tinyint(1)</td>
<td class='normal' valign='top'>NO</td>
<td class='normal' valign='top'></td>
<td class='normal' valign='top'>NULL</td>
<td class='normal' valign='top'></td>
</tr>

<tr>
<td class='normal' valign='top'>createDate</td>
<td class='normal' valign='top'>datetime</td>
<td class='normal' valign='top'>NO</td>
<td class='normal' valign='top'></td>
<td class='normal' valign='top'>NULL</td>
<td class='normal' valign='top'></td>
</tr>

<tr>
<td class='normal' valign='top'>createdBy</td>
<td class='normal' valign='top'>varchar(40)</td>
<td class='normal' valign='top'>NO</td>
<td class='normal' valign='top'></td>
<td class='normal' valign='top'>NULL</td>
<td class='normal' valign='top'></td>
</tr>

<tr>
<td class='normal' valign='top'>lastUpdate</td>
<td class='normal' valign='top'>timestamp</td>
<td class='normal' valign='top'>NO</td>
<td class='normal' valign='top'></td>
<td class='normal' valign='top'>CURRENT_TIMESTAMP</td>
<td class='normal' valign='top'>on update CURRENT_TIMESTAMP</td>
</tr>

<tr>
<td class='normal' valign='top'>lastUpdateBy</td>
<td class='normal' valign='top'>varchar(40)</td>
<td class='normal' valign='top'>NO</td>
<td class='normal' valign='top'></td>
<td class='normal' valign='top'>NULL</td>
<td class='normal' valign='top'></td>
</tr>
</table>

error trace:

System.Exception
HResult=0x80131500
Message=couldn't update the customer because: System.InvalidCastException: Specified cast is not valid.
at MySql.Data.MySqlClient.MySqlDataReader.GetFieldValue[T](Int32 ordinal)
at lambda_method(Closure , DbDataReader )
at Microsoft.EntityFrameworkCore.Storage.Internal.TypedRelationalValueBufferFactory.Create(DbDataReader dataReader)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean
buffer)
at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3
operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at lambda_method(Closure )
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable`1.GetEnumerator()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__17`2.MoveNext()
    at
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.<CompileQueryCore>
        b__0(QueryContext qc)
        at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
        at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
        at System.Linq.Queryable.First[TSource](IQueryable`1 source, Expression`1 predicate)
        at Scheduler.Data.CustomerDao.UpdateCustomerById(Int32 id, String updatedName, Int32 updatedAddressId)
        Source=Scheduler.Data
        StackTrace:
        at Scheduler.Data.CustomerDao.UpdateCustomerById(Int32 id, String updatedName, Int32 updatedAddressId) in
        C:\Users\source\repos\Scheduler\Scheduler.Data\CustomerDao.cs:line 79
        at Scheduler.Dashboard.ApplyChangesButton_Click(Object sender, EventArgs e) in
        C:\Users\source\repos\Scheduler\Scheduler\Dashboard.cs:line 112
        at System.Windows.Forms.Control.OnClick(EventArgs e)
        at System.Windows.Forms.Button.OnClick(EventArgs e)
        at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
        at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
        at System.Windows.Forms.Control.WndProc(Message& m)
        at System.Windows.Forms.ButtonBase.WndProc(Message& m)
        at System.Windows.Forms.Button.WndProc(Message& m)
        at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
        at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
        at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr
        lparam)
        at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
        at
        System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr
        dwComponentID, Int32 reason, Int32 pvLoopData)
        at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext
        context)
        at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
        at System.Windows.Forms.Application.Run(Form mainForm)
        at Scheduler.Program.Main() in C:\Users\source\repos\Scheduler\Scheduler\Program.cs:line 19

Any thoughts or noticeable flaws on why this one method in particular isn't working would be great, thanks

1
0
6/4/2019 7:46:03 AM

Accepted Answer

The solution that I found to this issue was to update the tinyint(1) to a tinyint(3). Changing that fixed the casting errors as entity framework was able to work with it as you'd expect. The gotcha is in the CLI which makes it a tinyint(1) by default, so updating it to a tinyint(3) after the fact should fix it.

0
12/31/2019 6:05:15 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow