efcore.pg icon indicating copy to clipboard operation
efcore.pg copied to clipboard

Can't cast database type char to String

Open jesperlandmer opened this issue 6 years ago • 3 comments

With target framework netcoreapp3.1, using a PostgreSQL database with NpgSQL Nuget Package (v. 3.1.4), I have a column my_column with type char containing numbers and characters, e.g.:

> SELECT DISTINCT my_column FROM my_table;
  my_column 
-----------------------
 2
 1
 0
 d

When trying to access the properties with the Entity Framework :

modelBuilder.Entity<MyModel>(entity =>
{
  entity.Property(e => e.MyColumn)
   .HasColumnName("my_column")
   .HasColumnType("char");
}

With MyModel like:

public partial class MyModel
{
     public string MyColumn { get; set; }
}

I get this error (when requesting the data from my controller):

System.InvalidCastException: Can't cast database type char to String
   at Npgsql.NpgsqlDataReader.GetFieldValue[T](Int32 ordinal)
   at Npgsql.NpgsqlDataReader.GetString(Int32 ordinal)
   at lambda_method(Closure , QueryContext , DbDataReader , ResultContext , Int32[] , ResultCoordinator )
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Controllers.Controller.Get() in ~/Controllers/Controller.cs:line 31
   at lambda_method(Closure , Object )
   at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Does this have to do with some char-values in my table being numbers? Are they interpreted as ints instead?

jesperlandmer avatar Jun 03 '20 12:06 jesperlandmer

The below code sample works for me, can you pleased tweak it so that it fails as it does for you?

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

        ctx.Blogs.Add(new Blog { Name = "f" });
        await ctx.SaveChangesAsync();

        var blog = ctx.Blogs.Single();
        Console.WriteLine(blog.Name);
    }
}

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

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql(@"Host=localhost;Database=test;Username=npgsql_tests;Password=npgsql_tests")
            .EnableSensitiveDataLogging()
            .UseLoggerFactory(ContextLoggerFactory);

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Blog>()
            .Property(b => b.Name)
            .HasColumnType("char");
    }
}

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }
}

roji avatar Jun 07 '20 17:06 roji

Closing as no answer was provided.

roji avatar Jul 23 '20 07:07 roji

I realise this is closed but I'll post what happened for me for if anyone comes to this issue in the future.

I had an existing database (not generated by EF migrations) and I had a column of type "char" (not char). From the Postgres docs

The type "char" (note the quotes) is different from char(1) in that it only uses one byte of storage.

To get this to work I had to use .HasColumnType("char(1)"), rather than .HasColumnType("char"). I also tried .HasColumnType("\"char\"") but it then wanted to apply a new migration as it had the type as char(1) in the model.

donaldgray avatar Oct 12 '21 06:10 donaldgray