一  背景

  今天在使用EntityFrameworkCore 查询的时候在调试的时候总是提示如下错误:Unable to cast object of type 'System.Data.SqlTypes.SqlString' to type 'System.Data.SqlTypes.SqlGuid' 第一次看这个报错肯定是数据库实体和EFCore中定义的某种类型不匹配从而导致类型转换错误,但是业务涉及到这么多的实体Entity,那么到底是哪里类型无法匹配呢?所以第一步肯定是调试代码,然后看报错信息,这里我们首先贴出完整的报错信息,从而方便自己分析具体问题。  

System.InvalidCastException: Unable to cast object of type 'System.Data.SqlTypes.SqlString' to type 'System.Data.SqlTypes.SqlGuid'.
at System.Data.SqlClient.SqlBuffer.get_SqlGuid()
at System.Data.SqlClient.SqlDataReader.GetGuid(Int32 i)
at lambda_method(Closure , DbDataReader )
at Microsoft.EntityFrameworkCore.Storage.Internal.TypedRelationalValueBufferFactory.Create(DbDataReader dataReader)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func` operation, Func` verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider._TrackEntities[TOut,TIn](IEnumerable` results, QueryContext queryContext, IList` entityTrackingInfos, IList` entityAccessors)+MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`.EnumeratorExceptionInterceptor.MoveNext()
at System.Linq.Lookup`.CreateForJoin(IEnumerable` source, Func` keySelector, IEqualityComparer` comparer)
at System.Linq.Enumerable.JoinIterator[TOuter,TInner,TKey,TResult](IEnumerable` outer, IEnumerable` inner, Func` outerKeySelector, Func` innerKeySelector, Func` resultSelector, IEqualityComparer` comparer)+MoveNext()
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable` source, Func` keySelector, Func` elementSelector, IEqualityComparer` comparer)
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable` source, Func` keySelector, Func` elementSelector)
at Sunlight.Dcs.Application.Sales.SalesOrder.DegradedVehicleContracts.DegradedVehicleContractService.QueryByIdAsync(Int32 id) in E:\\sales-service\src\sales.orders\Application.Sales.Orders\SalesOrder\DegradedVehicleContracts\DegradedVehicleContractService.cs:line
at Abp.Threading.InternalAsyncHelper.AwaitTaskWithPostActionAndFinallyAndGetResult[T](Task` actualReturnValue, Func` postAction, Action` finalAction)
at Sunlight.Dcs.WebApi.Sales.Controllers.Orders.DegradedVehicleContractController.QueryById(Int32 id) in E:\\sales-service\src\WebApi.Sales\Controllers\Orders\DegradedVehicleContractController.cs:line
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at System.Threading.Tasks.ValueTask`.get_Result()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextExceptionFilterAsync()

  二  解决方案

  有了上面的报错信息我们就能够知道大致方向,接下来我们首先来看看报错信息的这段代码。

public async Task<SimpleDegradedVehicleContractOutput> QueryByIdAsync(int id) {
var queryResult = await _degradedVehicleContractRepository.GetAll()
.Include(d => d.DegradedVehicleContractDetails)
.SingleOrDefaultAsync(mp => mp.Id == id);
if (queryResult == null)
throw new ValidationException($"当前Id为:{id}的降级车合同没有找到");
var result = _objectMapper.Map<SimpleDegradedVehicleContractOutput>(queryResult);
result.Details = _objectMapper.Map<List<DegradedVehicleContractDetailDto>>(queryResult.DegradedVehicleContractDetails); //获取ProductId
var productIds = queryResult.DegradedVehicleContractDetails.Select(d => d.ProductId).Distinct().ToArray();
//车辆Id
var vinLists = queryResult.DegradedVehicleContractDetails.Select(r => r.Vin).Distinct().ToArray(); var detailResult = (from detail in queryResult.DegradedVehicleContractDetails
join product in _productRepository.GetAll().Where(p => productIds.Contains(p.Id))
on detail.ProductId equals product.Id
join vehicleDict in _vehicleInformationRepository.GetAll().Where(v => vinLists.Contains(v.Vin))
on detail.Vin equals vehicleDict.Vin
select new {
ProductId = product.Id,
product.ProductType,
VehicleId = vehicleDict.Id,
detail.Vin
}).ToDictionary(r => Tuple.Create(r.ProductId, r.Vin), r => new { r.ProductType, r.VehicleId }); result.Details.ForEach(r => {
r.ProductType = detailResult[Tuple.Create(r.ProductId, r.Vin)]?.ProductType;
r.VehicleId = detailResult[Tuple.Create(r.ProductId, r.Vin)].VehicleId;
}); return result;
}

  2.1 定位报错位置

  通过直接对代码进行调试,我们发现只要代码执行获取detailResult这一步的时候就会出现上面的错误,那么到这里我们就可以推断错误的地方就在这里了,所以后面我们的重点就是分析这段代码。

  2.2 定位产生错误的表名称

  这里就是利用前面的Include方法来查询到queryResult结果,然后利用queryResult.DegradedVehicleContractDetails来和Product以及VehicleInformation表来做inner join,这里你可能对_productRepository以及_vehicleInformationRepository这个局部变量不是十分熟悉,那么我们先来看看这个局部变量的定义以及初始化。  

 private readonly IRepository<Product> _productRepository;
private readonly IRepository<VehicleInformation> _vehicleInformationRepository;

  上面是局部变量的定义,在我们的示例代码中我们使用ABP框架来作为整个项目代码的基础框架,这里的IRepository接口来自于ABP框架中定义的接口类型用于直接操作数据库表,这里具体的实现就是通过构造函数来进行注入的,具体请参考下面的实例。

public DegradedVehicleContractService(IObjectMapper objectMapper,
IRepository<DegradedVehicleContract> degradedVehicleContractRepository,
IRepository<Product> productRepository,
IRepository<VehicleInformation> vehicleInformationRepository,
IRepository<Company> companyRepository,
IDegradedVehicleContractManager degradedVehicleContractManager,
IRepository<ProductAffiProductCategory> productAffiProductCategoryRepository,
IRepository<ProductCategoryBusinessDomain> productCategoryBusinessDomainRepository,
IRepository<TiledProductCategory> tiledProductCategoryRepository,
IRepository<BusinessDomain> businessDomainRepository,
IMapper autoMapper) {
_objectMapper = objectMapper;
_degradedVehicleContractRepository = degradedVehicleContractRepository;
_productRepository = productRepository;
_vehicleInformationRepository = vehicleInformationRepository;
_companyRepository = companyRepository;
_degradedVehicleContractManager = degradedVehicleContractManager;
_productAffiProductCategoryRepository = productAffiProductCategoryRepository;
_productCategoryBusinessDomainRepository = productCategoryBusinessDomainRepository;
_tiledProductCategoryRepository = tiledProductCategoryRepository;
_businessDomainRepository = businessDomainRepository;
_autoMapper = autoMapper;
}

  有了上面的注释,相信你对上面那部分代码可以有更加深入的理解,回到正题,这里到底是Product实体中的问题还是VehicleInformation实体中存在问题呢?我们首先将

join vehicleDict in _vehicleInformationRepository.GetAll().Where(v => vinLists.Contains(v.Vin))   on detail.Vin equals vehicleDict.Vin

  这个部分注释掉,然后再调试代码,我们发现代码竟然不报错了,然后初步判断VehicleInformation这张表里面有问题,然后我们接着注释掉第二部分而保留第三部分,其中注释的部分代码为:

join product in _productRepository.GetAll().Where(p => productIds.Contains(p.Id))  on detail.ProductId equals product.Id

  经过这部分的操作以后,我们发现执行报错,有了这两步的验证之后我们更加确认是VehicleInformation表中存在类型不匹配的问题,然后我们接着往下进行分析。

  2.3 定位报错字段

  既然报错信息中是SqlTypes.SqlString'和SqlTypes.SqlGuid之间的转换有问题那么我们断定有一个字段数据库中定义的类型和实体中定义的类型不匹配,而且其中有一种是guid类型,由于我们的实体中guid类型的字段要少于string类型的字段,所以我们首先从guid类型下手,我们看看VehicleInformation中是否有哪种guid类型和数据库不匹配。然后还真的发现了这个类型 public Guid UnionId { get; set; },在我们的实体中定义了一个guid类型的字段UnionId这个是在迁移过程迁移到数据库的,然后我们来查看数据库中的类型。

图一 数据库中UnionId字段类型

  通过查询数据库我们发现数据库中字段UnionId被定义成了varchar(50)类型,明显在和代码中guid类型进行匹配的时候会发生错误,后来我很疑惑我们的开发模式是采用Code First来进行开发的,现有实体然后再通过Migration进行数据库迁移的,应该不会出现这样的错误,事后得知是另外一位同事在开发的过程中手动去更改了这个实体的类型从而导致了这个问题,最后更改数据库UnionId字段类型,然后发现错误消失,至此问题解决。

  总结

  这篇文章写作的主要目的是如果从一个大致方向来一步步去缩小错误范围,最终来一步步找出错误的根源,最终来解决问题,在这个过程中通过注释掉部分代码来缩小判断范围确实非常有用,另外用到的一个重要的知道思想就是“大胆假设小心求证”的思想来一步步分析问题,然后找到问题的根源,最终解决问题,所以有了上述分析问题解决问题的方法,我们就能够以后解决这一类型的问题,真正做到掌握这一类型问题的解决方法。

最新文章

  1. typedef 和 #define 的区别
  2. Java基础-关于session的详细解释
  3. Mac 下 Intellij IDEA 2016.1.2+maven+jetty+ JRebel 6.4.3 破解+spring mvc
  4. 使用RMAN对控制文件进行restore
  5. [转贴]sizeof 和strlen的区别
  6. FreeSwitch安装和配置记录
  7. flume1.8 Sinks类型介绍(三)
  8. 安全性测试:OWASP ZAP使用入门指南
  9. shell中的数据生命周期scope
  10. [转帖]Linux分页机制之概述--Linux内存管理(六)
  11. lettuce行为驱动总结
  12. Linux用户密码策略
  13. java-代码块-局部代码块、构造代码块、静态代码块
  14. C#构造方法--实例化类时初始化的方法
  15. ELK学习笔记之ELK分析nginx日志
  16. Python3: Command not found(Mac OS)
  17. poj1273&amp;&amp;hdu1532
  18. Java并发(四):happens-before
  19. java selector
  20. 基于opencv的摄像头的标定

热门文章

  1. goland 安装破解
  2. 模板 - 图论 - 强连通分量 - Kosaraju算法
  3. SSH如何使用
  4. [WEB安全]伪造IP地址进行爆破的BurpSuite插件:BurpFakeIP
  5. PKUWC2020 游记
  6. Tomcat学习四步走:内核、集群、参数及性能
  7. JS 读取 获取 cookie
  8. Python之pygame学习绘制文字制作滚动文字
  9. Nginx-实践篇(重要)
  10. phpstorm 使用xdebug断点