Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting bool to DateTime throws InvalidCastException #25475

Closed
pekspro opened this issue Aug 10, 2021 · 1 comment
Closed

Converting bool to DateTime throws InvalidCastException #25475

pekspro opened this issue Aug 10, 2021 · 1 comment

Comments

@pekspro
Copy link

pekspro commented Aug 10, 2021

File a bug

"Removed" is a bool in the Blog-entity, this line will throw System.InvalidCastException.

var blogs = await context.Blog.Select(b => new
{
    RemoveDate = b.Removed ? new DateTime(2000, 1, 1) : new DateTime(1900, 1, 1)
}).ToListAsync();

Maybe this is the same as: #24075

Sample code

using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace EfCoreBoolToDateIssue
{
    public class Blog
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public bool Removed { get; set; }
    }


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

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EfCoreBoolToDateIssue;Trusted_Connection=True;ConnectRetryCount=0")
                .LogTo(message => Console.WriteLine(message));

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        }
    }

    public static class Program
    {
        static async Task Main(string[] args)
        {
            using (var context = new BlogContext())
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                context.Add(new Blog
                {
                    Title = "Hello world",
                    Removed = true
                });

                context.SaveChanges();
            }

            using (var context = new BlogContext())
            {
                var blogs = await context.Blog.Select(b => new
                {
                    Title = b.Title,

                    // Next line will trigger System.InvalidCastException:
                    // 'Unable to cast object of type 'System.String' to type 'System.DateTime'.'
                    //
                    // This is the generated SQL:
                    // SELECT[b].[Title],
                    //                CASE
                    //      WHEN[b].[Removed] = CAST(1 AS bit) THEN '2000-01-01T00:00:00.0000000'
                    //      ELSE '1900-01-01T00:00:00.0000000'
                    //  END AS[RemoveDate]
                    //  FROM[Blog] AS[b]

                    RemoveDate = b.Removed ? new DateTime(2000, 1, 1) : new DateTime(1900, 1, 1)

                    // This is a workaround
                    // RemoveDate = DateTime.Parse(b.Removed ? "2000-01-01" : "1900-01-01")
                }).ToListAsync();
            }
        }
    }
}

Project file

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0-preview.6.21352.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="6.0.0-preview.6.21352.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.0-preview.6.21352.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0-preview.6.21352.1" />
  </ItemGroup>

</Project>

Stack trace

Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.DateTime'.
   at Microsoft.Data.SqlClient.SqlBuffer.get_DateTime() in Microsoft.Data.SqlClient.dll:token 0x6000a48+0x76
   at Microsoft.Data.SqlClient.SqlDataReader.GetDateTime(Int32 i) in Microsoft.Data.SqlClient.dll:token 0x6000d39+0x9
   at lambda_method39(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator )
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync() in Microsoft.EntityFrameworkCore.Relational.dll:token 0x6001b0f+0x1aa
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken) in Microsoft.EntityFrameworkCore.dll:token 0x6000214+0xcc
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken) in Microsoft.EntityFrameworkCore.dll:token 0x6000214+0x159
   at EfCoreBoolToDateIssue.Program.Main(String[] args) in C:\Users\msn\source\repos\EfCoreBoolToDateTimeIssue\EfCoreBoolToDateTimeIssue\Program.cs:line 51
   at EfCoreBoolToDateIssue.Program.<Main>(String[] args) in EfCoreBoolToDateTimeIssue.dll:token 0x6000014+0xc

Include provider and version information

EF Core version: 6.0.0-preview.6.21352.1
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 6.0
IDE: Command line

Also tried in .NET 5 and EF Core 5 with the same result.

@smitpatel
Copy link
Contributor

Duplicate of #24075

@smitpatel smitpatel marked this as a duplicate of #24075 Sep 10, 2021
@smitpatel smitpatel removed this from the 6.0.0 milestone Sep 10, 2021
@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants