vb-consulting / Norm.net

Norm.net is an innovative and high-performance Database Access for .NET Standard 2.1 and higher
https://vb-consulting.github.io/norm.net/
MIT License
176 stars 11 forks source link

Can't map null value to non-nullable property (which is nullable) #29

Open goncalo-oliveira opened 4 months ago

goncalo-oliveira commented 4 months ago
.NET 8
Norm.net 5.4.0
PostgreSQL 15.1 (Ubuntu 15.1-1.pgdg20.04+1) on aarch64-unknown-linux-gnu

Hi,

I'm seeing the following mapping error

Can't map null value for database field "claims" to non-nullable property "Claims".

Except that the Claims property is actually nullable, so the mapping should have worked I think.

The claims field in the database is an array and it is NULL at this point, yes.

claims text[] null,

In the same way, the class property is a nullable array

public string[]? Claims { get; set; }

Am I missing something?

vbilopav commented 4 months ago

Hi,

there are some limitations to the mapping of the nullable arrays, described here: https://vb-consulting.github.io/norm.net/docs/reference/read/#arrays-and-enums

I believe you can mitigate those limitations by using DbReader callback: https://vb-consulting.github.io/norm.net/docs/reference/read/#dbreader-callback

Also, reference here: https://vb-consulting.github.io/norm.net/docs/reference/methods/#withreadercallback

But unfortunately, the DbReader callback isn't that elegant and straightforward.

goncalo-oliveira commented 4 months ago

Hi @vbilopav,

Thanks for the quick response. Seems like the quick workaround is indeed to use the DbReader callback, as you suggested.

            var account = await connection.WithReaderCallback( p =>
            {
                // resolve as null
                if ( p.Reader.IsDBNull( p.Ordinal ) )
                {
                    return DBNull.Value;
                }

                return null;
            } )
            .ReadAsync<Account>( sql, parameters )
            .FirstOrDefaultAsync();

Although it seems like this is something that could easily be supported, since all I'm doing in the callback is to check if the value is IsDBNull; there's no data type checks or whatsoever. This doesn't mean that the actual implementation is that easy and I might not be seeing the big picture.

For the time being, I don't mind using this workaround, since I'll probably need it for jsonb types as well.

vbilopav commented 4 months ago

It's not easily supported. I've tried, and it's extremely difficult, given the current approach. It would have required me to rewrite everything from scratch.

goncalo-oliveira commented 4 months ago

Not worth the trouble then, I'd say.