【问题标题】:Why Entity Framework throws invalid cast为什么实体框架会抛出无效的演员表
【发布时间】:2019-06-04 04:19:16
【问题描述】:

无论我使用什么方法来查询数据,我都无法通过这种方法。它总是抛出一个错误:

指定的转换无效。

不知道为什么这个人会在选角上发疯。该列在 MySQL 中定义为INT(10),模型是ID 属性上的INT,输入变量是INT,但仍然存在转换错误!使用几乎完全相同的逻辑来创建、删除和getAllCustomer 方法可以正常工作。这是唯一的问题。

这里是有问题的方法:

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);
        }
}

型号:

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 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>

错误跟踪:

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

任何关于为什么特别是这种方法不起作用的想法或明显缺陷都会很好,谢谢

【问题讨论】:

  • 能否分享您的模型和异常堆栈跟踪。
  • 你为什么不做var customer = db.Customers.Find(customerId)
  • @gldraphael 因为那将是一个未定义的变量。传入的 int ID 变量是这样尝试的,但抛出了无效的强制转换。
  • 什么是未定义的变量?你也可以分享你的 DbContext 吗?
  • 我相信 MySQL 中的 Int(10) 在未签名时会超出 Int32 的范围。您可以尝试定义键。

标签: c# .net entity-framework casting entity-framework-core


【解决方案1】:

我发现这个问题的解决方案是将 tinyint(1) 更新为 tinyint(3)。更改修复了铸造错误,因为实体框架能够按照您的预期使用它。 gotcha 在 CLI 中,默认情况下它使其成为 tinyint(1),因此事后将其更新为 tinyint(3) 应该可以修复它。

【讨论】:

  • 请详细说明
  • 框架的默认设置是使用 tinyint(1),因此您必须明确将其设置为 tinyint(3) 才能使用 MySQL 获得正确的强制转换。如果这还不够,那你还需要什么?很高兴分享我所知道的一切!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
  • 2016-05-13
  • 2015-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多