Невозможно привести объект типа «пользовательский тип» к типу «System.Collections.IEnumerable» с помощью LiteDB. - PullRequest
0 голосов
/ 07 апреля 2020

Получение System.InvalidCastException при попытке сохранить пользовательские классы в коллекцию LiteDB.

Строка кода, в которой выдается ошибка:

using (var db = new LiteDatabase(_datastore))
    {
        var results = db.GetCollection<ImageResult>("ImageResults");
        ImageResult result;
        if (results.Exists(x => x.ImageName == Path.GetFileName(_currentFile)))
        {
            result = results.Find(x => x.ImageName == Path.GetFileName(_currentFile)).FirstOrDefault();
        }
        else
        {
            result = new ImageResult {_id = new Guid(), ImageName = Path.GetFileName(_currentFile)};
        }
    }

Я также пытался использовать results.FindOne() и используя формат condition ? consequent : alternative для запроса.

Я не уверен, что является причиной проблемы в моем классе. Я использую .NETFramework Version = v4.6.1 в проекте WinForms.

Классы следующие и сохраняются в своих собственных файлах CustomClasses.cs:

{
    public class SpatialSet
    {
        public Guid _id { get; set; }
        public String Name { get; set; }
        public FeatureType Type { get; set; }
        public List<List<PointF>> Points { get; set; }
        public Shapefile GenerateShapefile()
        {
            var s = new Shapefile{Name = Name, FeatureType =  Type};
            foreach (var pList in Points)
            {
                var c = pList.Select(x => new Coordinate(x.X, x.Y));
                s.Features.Add(c,Type);
            }

            return s;
        }

        public void FromShapefile(Shapefile shapefile)
        {
            _id = Guid.NewGuid();
            Name = shapefile.Name;
            Type = shapefile.FeatureType;
            var l = new List<List<PointF>>();
            foreach (var f in shapefile.Features)
            {
                var cLists = f.Coordinates;
                var pList = new List<PointF>() ;

                foreach (var coordinate in cLists)
                {
                    var p = new PointF((float)coordinate.X,(float)coordinate.Y);
                    pList.Add(p);
                }
                l.Add(pList);
            }
            Points = l;
        }

    }
    public  class ImageResult
    {
        public Guid _id { get; set; }
        public string ImageName { get; set; }
        public SpatialSet Points { get; set; }
        public SpatialSet Polygons { get; set; }
        public SpatialSet Circles { get; set; }

    }
}

Подробная информация о System.InvalidCastException сообщение об ошибке:

System.InvalidCastException: Unable to cast object of type 'ImageManipulation.SpatialSet' to type 'System.Collections.IEnumerable'.
  at at LiteDB.BsonMapper.DeserializeList(Type type, BsonArray value)
  at at LiteDB.BsonMapper.Deserialize(Type type, BsonValue value)
  at at LiteDB.BsonMapper.DeserializeObject(EntityMapper entity, Object obj, BsonDocument value)
  at at LiteDB.BsonMapper.Deserialize(Type type, BsonValue value)
  at at LiteDB.LiteQueryable`1.<ToEnumerable>b__27_2(BsonDocument x)
  at at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
  at at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
  at ImageManipulation.FrmMain.btnSaved_Click(Object sender, EventArgs e) in C:\Users\michael.thompson\RiderProjects\ImageManipulation\ImageManipulation\FrmMain.cs:337
  at at System.Windows.Forms.Control.OnClick(EventArgs e)
  at at System.Windows.Forms.Button.OnClick(EventArgs e)
  at at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
  at at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
  at at System.Windows.Forms.Control.WndProc(Message& m)
  at at System.Windows.Forms.ButtonBase.WndProc(Message& m)
  at at System.Windows.Forms.Button.WndProc(Message& m)
  at at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
  at at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
  at at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  at at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
  at at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
  at at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
  at at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
  at at System.Windows.Forms.Application.Run(Form mainForm)
  at ImageManipulation.Program.Main() in C:\Users\michael.thompson\RiderProjects\ImageManipulation\ImageManipulation\Program.cs:16

1 Ответ

0 голосов
/ 14 апреля 2020

Я запустил ваш пример (его упрощенную версию, потому что вы не предоставили все классы) и не смог воспроизвести проблему. Может быть, вы могли бы предоставить все классы, и я постараюсь выполнить полный пример.

...