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.

EF Core + Npgsql + NodaTime + linq2db - Cannot convert to DateTime

See original GitHub issue

I am having a weird bug when using Npgsql’s NodaTime bindings. Each non-NodaTime binding just breaks with the following exceptions:

Cannot convert value '2021-09-16T18:14:14Z' to type 'System.DateTime': Object must implement IConvertible.
   at LinqToDB.Common.ConvertBuilder.ConvertDefault(Object value, Type conversionType)
   at LinqToDB.Expressions.ConvertFromDataReaderExpression.ColumnReader.GetValue(IDataReader dataReader)
   at LinqToDB.Linq.QueryRunner.Mapper`1.Map(IDataContext context, IQueryRunner queryRunner, IDataReader dataReader)
   at LinqToDB.Linq.QueryRunner.AsyncEnumeratorImpl`1.<MoveNextAsync>d__18.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.<ToListAsync>d__65`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.<ToListAsync>d__65`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.<ToArrayAsync>d__66`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at LinqToDB.AsyncExtensions.<ToArrayAsync>d__9`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

The same query when run through EF Core works just fine, but breaks through Linq2Db.

I’ve set up a simple repro:

One-file repro
using LinqToDB.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;

namespace L2DbBugRepro
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await using (var ctx = new BlogContext())
            {
                await ctx.Database.EnsureDeletedAsync();
                await ctx.Database.EnsureCreatedAsync();

                ctx.Facts.Add(new Fact
                {
                    FactId = Guid.NewGuid(),
                    Date = DateTime.Now,
                });
                await ctx.SaveChangesAsync();
            }

            await using (var ctx = new BlogContext())
            {
                var facts = await ctx.Facts.ToArrayAsyncLinqToDB();
            }


        }
    }


    public class BlogContext : DbContext
    {
        public DbSet<Fact> Facts { get; set; }

        static ILoggerFactory ContextLoggerFactory
            => LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql(@"Host=localhost;Username=root;Password=rootpass;Database=Testing", n => n.UseNodaTime())
    .EnableSensitiveDataLogging()
                .UseLoggerFactory(ContextLoggerFactory);

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        }
    }

    public class Fact
    {
        [Key]
        public Guid FactId { get; set; }

        public DateTime Date { get; set; }
        // Other fields redacted
    }
}

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:25 (13 by maintainers)

github_iconTop GitHub Comments

1reaction
sdanylivcommented, Nov 8, 2021

Check latest version that have released today. It supports EF Core 6.0.0.

1reaction
sdanylivcommented, Nov 7, 2021

Probably you forgot to call ToLinqToDB(). Because it is EF Core exception.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Cannot write DateTime with Kind=UTC to PostgreSQL type ...
Same thing happened to me when my Controller deserialize the object and I was trying to insert/update it with EF and Npgsql.EntityFrameworkCore.
Read more >
Date and Time Handling
Starting with Npgsql 6.0, these special values are mapped to the MinValue and MaxValue value on the corresponding .NET types ( DateTime and...
Read more >
Supported Types and their Mappings
Consider using NodaTime's Period type, or NpgsqlInterval. The Default .NET type column specifies the data type NpgsqlDataReader.GetValue() will return.
Read more >
Mapping .NET Timestamps to PostgreSQL - Shay Rojansky
Reading a timestamptz will now yield a UTC DateTime or DateTimeOffset - no more implicit conversions. By nature, EF Core must make mapping ......
Read more >
EF core datetime2 conversion to datetime resulted in an ...
I cannot see why having assigned the value to the data row, it is not present when the row is attempting to save....
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