vb-consulting / norm.net Goto Github PK
View Code? Open in Web Editor NEWNorm.net is an innovative and high-performance Database Access for .NET Standard 2.1 and higher
Home Page: https://vb-consulting.github.io/norm.net/
License: MIT License
Norm.net is an innovative and high-performance Database Access for .NET Standard 2.1 and higher
Home Page: https://vb-consulting.github.io/norm.net/
License: MIT License
Hi,
I have a scenario where the parameters for a query/command are created dynamically. This means that, in order to use the object mapping functionality such as the one below is not possible out of the box.
connection.Read<T>( "select @p0, @p1", new { p0 = "value1", p1 = "value2" } );
To get around this issue, I am doing some nasty things that essentially turns a IDictionary<string, object?>
into an anonymous type.
It would be a great addition if we could construct a IDictionary<string, object?>
and use that as the parameters
argument.
connection.Read<T>( "select @p0, @p1", new Dictionary<string, object>
{
{ "p0", 1 },
{ "p1", "2" }
} );
Using Execute does not return the number of rows affected, How to get the number of affected rows?
for example:
connection.Execute("INSERT IGNORE INTO OrderDetails (id) values (@id)",new {id= "333"});
Prior versions of this library supported ReadAsync called with these generic parameters:
ReadAsync<string, TimeSpan?, TimeSpan?, string, bool>(sql)
But with newer versions this throws:
Norm.NormMultipleMappingsException: Multiple mappings requires types of same category:
Classes with classes, records with records, value tuples with value tuple and simple types with simple types.
For example pappings `Read<Class, int>` or `Read<int, Class>` are not permitted.
Would support for mapping for insert statements be something you're willing to look at?
If I do var record in conn.ReadAsync<dynamic>("select 1 as test_test)
the column name test_test
will be converted to expando key testtest
, I think due to this. Is there a reason to remove the underscores?
Is there a way to expand the object mapper with custom types?
I'm currently using an external object that use DateTimeOffset
on one of the properties, which is not among the basic supported types. I can't seem to find a way to work around that without mapping the object manually. For large objects that's a a bit unfortunate.
The syntax for doing a join query with multiple tables is interesting, but it seems to only work with INNER
joins. Let's consider we have an Assets
and a Vehicles
table, where there is an optional correspondence of 1-1. Here's what the query would look like (excluding grouping code for simplification).
var tuple = await connection.Cast()
.ReadAsync<Asset, Vehicle?>(
"""
select a.*, v.*
from assets a
left join vehicles v on a.id = v.id
"""
)
.ToListAsync();
If I change the query to an INNER JOIN
it works and I kind of expected the LEFT JOIN
to work also by setting a nullable in the tuple, but it doesn't.
If it's not a lot a work, I think this could be an interesting fix.
Would like to see benchmark which fulfils the claim.
I pulled your NormPgIdentity code, set the database up, did the migrations, then ran the program. Everything worked as published. I was very happy because I am no fan of EF. I started a new project, set it to botnet Core 5 and c# 9. Pulled the packages (latest ones), Norm.net/3.3.1, Npgsql/6.0.0=preiview, System.Linq.Async/5.0.0 and AspNetCore.Identity.UI/45.0.8.
I had to change UserStore and RoleStore to get the IDE to stop complaining. There were a couple other small items that I fixed. Ran the program. I was able to register a user. The data ended up correct in the database. All was good. However when I go to login I get an exception "InvalidCastException: Can't cast database type bigint to IdentityUser`1". It happens in the FindAsync function. This is what I changed it to:
private async Task<IdentityUser> FindAsync(CancellationToken cancellationToken, long? userId = null, string name = null, string email = null) =>
await _connection.WithCancellationToken(cancellationToken).ReadAsync<IdentityUser>($@"
select
{GetUserSelectRecord()}
from
""user"" u
where
( @id is null or u.id = @id ) and
( @name is null or u.normalized_user_name = @name ) and
( @email is null or u.normalized_email = @email )
", ("id", userId, DbType.Int64), ("name", name, DbType.String), ("email", email, DbType.String))
.FirstOrDefaultAsync(cancellationToken);
Did I not correct the above function correctly?
Thanks,
Bob
Hi there!
Are you planning to add support for custom types? like the SqlMapper.TypeHandler in Dapper?
thanks!
I've got a situation with a query that returns an hstore
type field. According to the driver docs, this type defaults to a Dictionary<string, string>
.
Here's the simplified query; removed unnecessary clutter for clarity
select
name,
tags::hstore
from planet_osm_roads
limit 1;
For this use case, I created a model class, which looks like this
internal sealed class RoadSegmentModel
{
public string? Name { get; set; }
public Dictionary<string, string>? Tags { get; set; }
}
The type mapping I think it's accurate, because if I change it to a string, I get the following exception, which would be expected
System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' to type 'System.String'.
So... the code to execute the query is pretty much straightforward
var result = await connection.ReadAsync<RoadSegmentModel>( sql )
.ToArrayAsync();
However, when executing this, I'm presented with the following exception
System.NotImplementedException: TypeCode Object not implemented
at Norm.Mapper.NormExtensions.CreateDelegate[T](PropertyInfo property, Boolean nullable)
at Norm.Mapper.NormExtensions.MapInstance[T](ReadOnlyMemory`1 tuple, T& instance, MapDescriptor& descriptor, ValueTuple`7[]& delegates)
at Norm.Mapper.NormExtensions.Map[T](IAsyncEnumerable`1 tuples, Type type1)+MoveNext()
at Norm.Mapper.NormExtensions.Map[T](IAsyncEnumerable`1 tuples, Type type1)+MoveNext()
at Norm.Mapper.NormExtensions.Map[T](IAsyncEnumerable`1 tuples, Type type1)+System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult()
Am I missing something here, maybe?
Hey, I'm trying to map a result of json_agg combined with normal columns.
This is the query:
select id, foo, json_agg(
json_build_object(
'Name1', t.name1,
'Name2', t.name2
)
) from (
values
(1, 'foo1', 'testname1', 'x'),
(2, 'foo2', 'testname2', 'y'),
(2, 'foo2', 'testfoo3', 'yy'),
(3, 'foo3', 'testname3', 'z')
) t(id, foo, name1, name2)
GROUP BY id, foo;
And I'm trying to map it with the following code:
connection.ReadAsync<FirstPart, JsonPart[]>(...)
public class FirstPart
{
public required int Id { get; init; }
public required string Foo { get; init; }
}
public class JsonPart
{
public required string Name1 { get; init; }
public required string Name2 { get; init; }
}
The following exception is thrown:
System.InvalidCastException: Can't cast database type integer to FirstPart
at Npgsql.Internal.TypeHandling.NpgsqlTypeHandler.ReadCustom[TAny](NpgsqlReadBuffer buf, Int32 len, Boolean async, FieldDescription fieldDescription)
at Npgsql.NpgsqlDataReader.GetFieldValue[T](Int32 ordinal)
at Npgsql.NpgsqlDataReader.GetFieldValueAsync[T](Int32 ordinal, CancellationToken cancellationToken)
at Norm.Norm.GetFieldValueAsync[T](DbDataReader reader, Int32 ordinal, Type type)
at Norm.Norm.<>c__DisplayClass108_0`2.<<ReadAsync>b__0>d.MoveNext()
--- End of stack trace from previous location ---
at Norm.Norm.ReadCallbackAsync[T](String command, Func`2 readerAction)+MoveNext()
It's working if I replace FirstPart with value types: ReadAsync<int, string, JsonPart[]>
. Maybe it's the proper way of doing it and I'm just doing weird stuff 😄
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.