【发布时间】:2020-08-19 22:37:22
【问题描述】:
使用 EF Core 3.1,我正在尝试使用以下代码从数据库 (SQL Server) 中获取表:
query = dbContext.Set<Entity>().ToList();
该代码适用于其他表,但在特定表上失败,并出现以下异常:
System.InvalidCastException: Unable to cast object of type 'System.Byte' to type 'System.Int32'.
at Microsoft.Data.SqlClient.SqlBuffer.get_Int32()
at Microsoft.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)
at lambda_method(Closure , QueryContext , DbDataReader , ResultContext , Int32[] , ResultCoordinator )
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
在 try-catch 中使用断点并没有帮助,因为内部异常为 null。如何判断哪个表列导致了强制转换异常?
型号代码:
[Table("Plugin")]
public partial class Plugin
{
public Plugin()
{
SetAPlugins = new HashSet<SetProfile>();
SetBplugins = new HashSet<SetProfile>();
SetBPlugins = new HashSet<SetProfile>();
SetBPlugins = new HashSet<SetProfile>();
SetBPlugins = new HashSet<SetProfile>();
}
[Key]
[Column("ID")]
public Guid ID { get; set; }
public int Serial { get; set; }
[Column(TypeName = "datetime")]
public DateTime? DateCreated { get; set; }
[Column(TypeName = "datetime")]
public DateTime? DateModified { get; set; }
public ObjectStatus ObjectStatus { get; set; }
[Required]
public byte[] Timestamp { get; set; }
public PluginType Type { get; set; }
[StringLength(64)]
public string Name { get; set; }
[StringLength(512)]
public string ProcessorAssembly { get; set; }
[StringLength(512)]
public string ProcessorClass { get; set; }
[StringLength(512)]
public string AdminAssembly { get; set; }
[StringLength(512)]
public string AdminClass { get; set; }
[StringLength(32)]
public string ConfigName { get; set; }
public ProfileType SubType { get; set; }
[StringLength(256)]
public string ContainerType { get; set; }
[StringLength(256)]
public string SupportedFeatures { get; set; }
[InverseProperty(nameof(SetProfile.SetAPlugin))]
public virtual ICollection<SetProfile> SetAPlugins { get; set; }
[InverseProperty(nameof(SetProfile.SetBplugin))]
public virtual ICollection<SetProfile> SetBPlugins { get; set; }
[InverseProperty(nameof(SetProfile.SetCPlugin))]
public virtual ICollection<SetProfile> SetCPlugins { get; set; }
[InverseProperty(nameof(SetProfile.SetDPlugin))]
public virtual ICollection<SetProfile> SetDPlugins { get; set; }
[InverseProperty(nameof(SetProfile.SetEPlugin))]
public virtual ICollection<SetProfile> SetEPlugins { get; set; }
}
【问题讨论】:
-
您的表和实体的映射似乎不正确。不看代码很难帮忙
-
代码不准确:你提到实体然后是插件。
-
什么是ObjectStatus和PluginType,它们是枚举吗?
-
是的,它们是枚举。
标签: c# ef-core-3.1