question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Question: Convert custom DateTime object to DateTime on insert

See original GitHub issue

Hello,

I am using t4 model generation and all of the DateTime properties have been converted to NodaTime.LocalDateTime.

When I am getting the data from the DB I am using this convertor successfully:

LinqToDB.Mapping.MappingSchema.Default.SetConverter<DateTime, NodaTime.LocalDateTime>(timeStamp =>
			new NodaTime.LocalDateTime(timeStamp.Year, timeStamp.Month, timeStamp.Day, timeStamp.Hour,
			timeStamp.Minute, timeStamp.Second, timeStamp.Millisecond));

The issue is when I try to submit data:

UserSession session = new UserSession
           {
               CreatedOn = NodaTime.LocalDateTime.FromDateTime(DateTime.Now),
           };

using (var db = new DBContext())
           {
                   await db.InsertAsync(session);
           }

The error is:

ArgumentException: No mapping exists from object type NodaTime.LocalDateTime to a known managed provider native type.
System.Data.SqlClient.MetaType.GetMetaTypeFromValue(Type dataType, object value, bool inferLen, bool streamAllowed)
System.Data.SqlClient.MetaType.GetMetaTypeFromType(Type dataType)
System.Data.SqlClient.SqlParameter.GetMetaTypeOnly()
lambda_method(Closure , IDbDataParameter )
LinqToDB.DataProvider.SqlServer.SqlServerDataProvider.SetParameter(DataConnection dataConnection, IDbDataParameter parameter, string name, DbDataType dataType, object value)
LinqToDB.Data.DataConnection+QueryRunner.AddParameter(DataConnection dataConnection, ICollection<IDbDataParameter> parms, string name, SqlParameter parm)
LinqToDB.Data.DataConnection+QueryRunner.GetParameters(DataConnection dataConnection, PreparedQuery pq)
LinqToDB.Data.DataConnection+QueryRunner.SetQuery(DataConnection dataConnection, IQueryContext queryContext, int startIndent)
LinqToDB.Data.DataConnection+QueryRunner.SetQuery()
LinqToDB.Linq.QueryRunnerBase.SetCommand(bool clearQueryHints)
LinqToDB.Data.DataConnection+QueryRunner.ExecuteNonQueryAsync(CancellationToken cancellationToken)
LinqToDB.Linq.QueryRunner.NonQueryQueryAsync(Query query, IDataContext dataContext, Expression expression, object[] ps, object[] preambles, CancellationToken cancellationToken)
LinqToDB.Linq.QueryRunner+Insert<T>.QueryAsync(IDataContext dataContext, T obj, InsertColumnFilter<T> columnFilter, string tableName, string serverName, string databaseName, string schemaName, CancellationToken token)

And the convertors that I have tried are:

LinqToDB.Mapping.MappingSchema.Default.SetDataType(typeof(LocalDateTime), LinqToDB.DataType.DateTime);
LinqToDB.Mapping.MappingSchema.Default.SetDataType(typeof(LocalDateTime), LinqToDB.SqlQuery.SqlDataType.DateTime);

LinqToDB.Mapping.MappingSchema.Default.SetConverter<NodaTime.LocalDateTime, DataParameter>(timeStamp =>
new DataParameter
{
	Value = new DateTime(timeStamp.Year, timeStamp.Month, timeStamp.Day, timeStamp.Hour,
timeStamp.Minute, timeStamp.Second, timeStamp.Millisecond),
        //Value = DateTime.Now,
	DataType = LinqToDB.DataType.DateTime
});

LinqToDB.Mapping.MappingSchema.Default.SetConverter<NodaTime.LocalDateTime, DateTime>(timeStamp =>
new DateTime(timeStamp.Year, timeStamp.Month, timeStamp.Day, timeStamp.Hour,
timeStamp.Minute, timeStamp.Second, timeStamp.Millisecond));

LinqToDB.Mapping.MappingSchema.Default.SetValueToSqlConverter
	(typeof(NodaTime.LocalDateTime), (sb, dt, v) =>
	{
		var d = (NodaTime.LocalDateTime)v;
		var d1 = new DateTime(d.Year, d.Month, d.Day, d.Hour,
		d.Minute, d.Second, d.Millisecond);

		sb.Append("'").Append(d1.ToString()).Append("'");
		//sb.Append("'").Append(d1).Append("'");
	}
	);

LinqToDB.Mapping.MappingSchema.Default.SetConverter<NodaTime.LocalDateTime, DataParameter>(timeStamp =>
new DataParameter
{
	Value = new DateTime(timeStamp.Year, timeStamp.Month, timeStamp.Day, timeStamp.Hour,
timeStamp.Minute, timeStamp.Second, timeStamp.Millisecond).ToString(),
	DataType = LinqToDB.DataType.NVarChar
});

Could you please give some directions of what am I missing here?

I have tried on Linq2DB.SqlServer versions 3.1.2 and 3.1.5

Thank you.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:10 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
carloscscommented, Nov 1, 2020

I’ve been testing Linq2db [mappings, optimistic locking,…] and this is working for me.

Setup:

LocalDateTimeToDatetimeConverter.RegisterConverters(schema);

Code:

public static class LocalDateTimeToDatetimeConverter {

    public static void RegisterConverters(MappingSchema schema) {
        schema.SetConverter<LocalDateTime?, DataParameter>(ldt => new DataParameter { Value = ldt?.ToDateTimeUnspecified() });
        schema.SetConverter<LocalDateTime, DataParameter>(ldt => new DataParameter { Value = ldt.ToDateTimeUnspecified() });

        schema.SetConverter<LocalDateTime?, DateTime?>(ldt => ldt?.ToDateTimeUnspecified());
        schema.SetConverter<LocalDateTime?, DateTime>(ldt => ldt.LocalDateTimeToDateTime());
        schema.SetConverter<LocalDateTime, DateTime?>(ldt => ldt.ToDateTimeUnspecified());
        schema.SetConverter<LocalDateTime, DateTime>(ldt => ldt.ToDateTimeUnspecified());

        schema.SetConverter<DateTime?, LocalDateTime?>(dt => dt == null ? (LocalDateTime?) null : LocalDateTime.FromDateTime(dt.Value));
        schema.SetConverter<DateTime?, LocalDateTime>(dt => dt.DateTimeToLocalDateTime());
        schema.SetConverter<DateTime, LocalDateTime?>(dt => LocalDateTime.FromDateTime(dt));
        schema.SetConverter<DateTime, LocalDateTime>(LocalDateTime.FromDateTime);

        schema.SetValueToSqlConverter(typeof(LocalDateTime?), ConverterToSql);
    }


    static DateTime LocalDateTimeToDateTime(this LocalDateTime? dateTime) {
        if (dateTime == null) {
            throw new InvalidOperationException("Can't convert null to LocalDateTime.");
        }
        return dateTime.Value.ToDateTimeUnspecified();
    }


    static LocalDateTime DateTimeToLocalDateTime(this DateTime? dateTime) {
        if (dateTime == null) {
            throw new InvalidOperationException("Can't convert null to LocalDateTime.");
        }
        return LocalDateTime.FromDateTime(dateTime.Value);
    }


    static void ConverterToSql(StringBuilder sb, SqlDataType tp, object v) {
        if (v == null) {
            sb.Append("NULL");
        }
        else {
            // todo: format date
            sb.Append($"TO_DATE('{v}', '%Y-%m-%d %H:%M:%S.%F5')");
        }
    }

}

0reactions
thedoomxcommented, Nov 10, 2020

Hi @carloscs

The provided solution worked perfectly for me.

Thank you!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Convert an unusual/custom time format to datetime object
Question : an easier way to accomplish it using datetime.datetime.strptime(). Split the datestring into parts: utc:[('1/3/2018 1:29:35 PM', ...
Read more >
Pandas Convert Date (datetime) to String Format
First, let's see how to convert the datetime (datetime64[ns]) column to String (object) type in pandas DataFrame. Use this approach If you ...
Read more >
insert datetime in a custom object
I have a datetime field in which I need to insert date and time - 5th ... http://salesforce.stackexchange.com/questions/36376/how-to-convert ...
Read more >
DateTime Tool
The DateTime tool transforms DateTime data to and from a variety of formats, including both expression-friendly and human readable formats.
Read more >
Parse date and time strings in .NET
The DateTime.ParseExact method converts a string to a DateTime object if it conforms to one of the specified string patterns. When a string...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found