marten icon indicating copy to clipboard operation
marten copied to clipboard

Exception when extracting Dictionary<,> property from Document

Open CSharpBender opened this issue 5 years ago • 3 comments

Hello, In my project I'm using Marten 2.10 with PostgreSQL 10.8. One of the documents contains a property of type Dictionary<int, T> which gets serialized as an object instead of array, which causes errors when querying the document. I've updated to the latest Marten version (3.6) but it's the same.

This is the class definition:

1. public class Program
2. {
3.   public int Id { get; set; }
4.   public Dictionary<int, LocalProperty> LocalProperties { get; set; }
5. }
6. public class LocalProperty
7. {
8.  public string Name { get; set; }
9.  public string Value{ get; set; }
10. }

This is how the object gets serialized

1. {
2.     "Id": 1,
3.     "LocalProperties ": {
4.         "1": { "Name": "MyName", "Value": "MyValue" },
5.         "2": {  "Name": "MyName2",  "Value": "MyValue2"	}
6.    }
7. }

Using both Marten 2.10 and 3.6 I'm getting these errors:

  1. Can't cast database type jsonb to Dictionary2 var props = _session.Query<Program>().Where(p => p.Id == 1).Select(p => p.LocalProperties ).FirstOrDefault();`

  2. Sequence contains no elements var props = _session.Query<Program>().Where(p => p.Id == 1).SelectMany(p => p.LocalProperties).ToList();

  3. ERROR: cannot get array length of a non-array SQL state: 22023 var props = _session.Query<Program().Where(p => p.Id == 1 && p.LocalProperties!=null).FirstOrDefault();

Basically the problem is that the Dictionary gets saved as an object but it's queried as an array.

CSharpBender avatar Jun 26 '19 09:06 CSharpBender

Thanks for the report. Another day, another LINQ-related bug (at least some field location issues in this case methinks }:] ). We'll investigate.

Meanwhile, if you really need to, you can materialize the query e.g. before the SelectMany (var props = _session.Query<Program>().Where(p => p.Id == 1).ToList().SelectMany(p => p.LocalProperties);).

jokokko avatar Jun 26 '19 12:06 jokokko

Thanks for the workaround but this is how it's done right now. I was trying to extract only the part that I need, because the document is big.

CSharpBender avatar Jun 26 '19 12:06 CSharpBender

I think this fixed via https://github.com/JasperFx/marten/pull/2057 (available in latest v5 alpha), will recheck and see if this can be closed.

mysticmind avatar Mar 04 '22 13:03 mysticmind

This was fixed by #2057

jeremydmiller avatar Aug 22 '22 15:08 jeremydmiller