Как определить, какой столбец таблицы вызывает недопустимое исключение приведения типов? - PullRequest
0 голосов
/ 05 мая 2020

Используя EF Core 3.1, я пытаюсь получить таблицу из базы данных (SQL Сервер), используя следующий код:

query = dbContext.Set<Entity>().ToList();

Код работает для других таблиц, но не работает на Speci c table со следующим исключением:

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

Я приложил снимок экрана столбцов БД из SSMS. enter image description here

Ответы [ 3 ]

3 голосов
/ 05 мая 2020

Проблема:

public ObjectStatus ObjectStatus { get; set; }

& Перечисление должно быть создано следующим образом:

public enum ObjectStatus : byte
{
    //List of values
}
0 голосов
/ 05 мая 2020

Проблема заключалась в том, что тип SQL - это tinyint, который является байтовым кодом и не может быть неявно преобразован в перечисление. Я использовал следующий код, чтобы решить эту проблему:

        [Column("ObjectStatus")]
        public Byte objectStatus { get; set; }

        [NotMapped]
        public ObjectStatus ObjectStatus
        {
            get
            {
                if (objectStatus > 0)               
                    return (ObjectStatus)objectStatus;            
                else
                    return ObjectStatus.Active;
            }
            set
            {
                objectStatus = (Byte)value;
            }
        }
0 голосов
/ 05 мая 2020

Вы отображаете свойство как int, которое должно быть byte, и только одно свойство отображается как int, то есть Serial, так что это должно быть единственное.

...