Efcore: Unable to cast object of type 'ConcreteTypeMapping' to type 'Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping'

Created on 17 Apr 2018  Â·  27Comments  Â·  Source: dotnet/efcore

public abstract class MultiLangEntity
{        
    [StringLength(3)]
    public string LanguageCode { get; set; }

    [ForeignKey("LanguageCode")]        
    public virtual Language Language { get; set; }

    [StringLength(50)]
    public virtual string Content { get; set; }
}

public class CountryDescription : MultiLangEntity
{
    [ForeignKey("CountryCode")]
    public virtual Country Country { get; set; }

    [StringLength(3)]
    public string CountryCode { get; set; }        
}

Initially, I use EF Core 2.0. The above code works. Then I realized lazy load only supported by EF Core 2.1. When I swift to "EF core 2.1.0-preview2-final", I encounter following exceptions.

System.InvalidCastException: Unable to cast object of type 'ConcreteTypeMapping' to type 'Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping'.
at Microsoft.EntityFrameworkCore.Metadata.RelationalPropertyAnnotations.get_ColumnType()
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerTypeMapper.GetColumnType(IProperty property)
at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapper.FindMapping(IProperty property)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.RelationalTypeMappingConvention.Apply(InternalModelBuilder modelBuilder)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelBuilt(InternalModelBuilder modelBuilder)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
at System.Lazy1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy1.CreateValue() at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model() at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure1 accessor)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func1 factory) at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_01.b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

closed-question

Most helpful comment

@mgolois When using ASP.NET Core, you need to update to the latest .NET Core SDK, as described in the ASP.NET Core 2.1 preview2 announcement. Currently you still have .NET Core 2.0 and ASP.NET Core 2.0 referenced, with only some EF packages updated to the 2.1 versions. This configuration will not work. Updating all the EF packages may work, but is not recommended--the recommended path is to install the new SDK.

All 27 comments

+1
I'm getting the same error. I worked of EF Core 2.0, but not with "EF core 2.1.0-preview2-final"

@Bo-Yee-Woods @mgolois Can you provide a runnable project/solution or complete code listing that demonstrates the behavior you are seeing? Also, what database provider and version are you using?

@ajcvickers I created a repo at https://github.com/mgolois/EFCore-ConcreteTypeMapping-Bug
The database is pretty simple:
DatabaseName: Database1 and TableName: Table1

USE [Database1]

CREATE TABLE [dbo].[Table1]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](max) NULL,
    [NameId] [int] NULL,
) 

@mgolois When using ASP.NET Core, you need to update to the latest .NET Core SDK, as described in the ASP.NET Core 2.1 preview2 announcement. Currently you still have .NET Core 2.0 and ASP.NET Core 2.0 referenced, with only some EF packages updated to the 2.1 versions. This configuration will not work. Updating all the EF packages may work, but is not recommended--the recommended path is to install the new SDK.

gotcha!
I also see that in order to update to the latest .NET Core SDK, I have first to install at least Visual Studio Visual Studio 2017 15.7 Preview 1

@ajcvickers Oh no! To make lazy loading using proxy to work, do I also need to use .net core 2.1 sdk? I follow tutorials and cannot work, very sad!

@Bo-Yee-Woods If you are using ASP.NET Core, then yes, that's the recommended approach.

@Bo-Yee-Woods Which tutorials were you attempting to follow?

@ajcvickers the tutorial is https://docs.microsoft.com/en-us/ef/core/querying/related-data . I hope .net core 2.1 and EF core 2.1 go production soon, lazy loading is important

hi guys, I updated my sdk, I currently have version 2.1.300-preview2-008533, but the problem still persists, my version of vs is 15.6.6. Is there any news about it?

@MoyaSoftInk Can you provide a runnable project/solution or complete code listing that demonstrates the behavior you are seeing? Also, what database provider and version are you using?

i'm using Microsoft SQL Server 2016 (RTM-GDR) (KB4019088) - 13.0.1742.0 (X64), i installed Net Core 2.1.0 and finally i'm trying implement LazyLoad-proxy using the tutorial https://docs.microsoft.com/en-us/ef/core/querying/related-data

image

@MoyaSoftInk Can you provide a runnable project/solution or complete code listing that demonstrates the behavior you are seeing?

I get these same error messages when trying to add-migration and also when debugging

It worked for me after I updated all my projects where I previously had EFCore installed to 2.1.0-preview2-final prerelease

For anyone reading this thread: if you are seeing these errors, then it likely means you have package version mismatch, as has been described in previous posts. If you are still seeing this after updating either SDK (for ASP.NET Core apps) or all EF package versions (for other apps) then please post a project/solution that exhibits the behavior you are seeing.

@ajcvickers Greetings, I made a mistake and did not update certain packages to net core 2.1, then it worked correctly. Thanks for your help.

Hi MoyaSoftInk,

Did it work for you without having to install version 15.7 preview of Visual Studio?

Hi @yob171182
I have the version 15.6.7 and work fine

just update all package Microsoft.EntityFrameworkCore.XXXX and Microsoft.AspNetCore.XXXX to prerelease versions (2.1.0-preview2-final

image

Me too....Thanks

On May 3, 2018 8:50 AM, "José Moya" notifications@github.com wrote:

Hi @yob171182 https://github.com/yob171182
I have the version 15.6.7 and work fine

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/aspnet/EntityFrameworkCore/issues/11704#issuecomment-386284368,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ALJFwk-P6PUvNrDsvZjfydO9vp8Q29Diks5tuv0TgaJpZM4TX2Ye
.

@yob171182 work fine?

I resolved this by ensuring all the Microsoft.EntityFrameworkCore.XXXX were updated. I left the ASP.NET Core 2.0.5 and SDK at 2.0. It got rid of this error and everything seems to work. Is there some gotcha here I'm missing?

Hi, I'm still getting this error on v2.1.0 stable of Microsoft.EntityFrameworkCore (also v2.1.0-preview2-final, 2.0.3)

        private readonly DbContext _context;
        private readonly DbSet<T> _set;

        public EntityDataSource(DbContext context)
        {
            _context = context;
            _set = _context.Set<T>(); //Error here
        }

I'm using an InMemory database with Dependency Injection:

        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = @"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;ConnectRetryCount=0";

            services.AddDbContext<ModelContext>(
                options => options.UseSqlServer(connectionString));

And if it helps, the model in question is:

    public class Giving
    {
        [Key]
        public Int64 Id { get; set; }
        public string Email { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTimeOffset CreatedUTC { get; set; }
        public override string ToString()
        {
            return $"{Id}";
        }
    }

This is a fairly new project, there aren't any other models declared.

For anyone reading this thread: if you are seeing these errors, then it likely means you have package version mismatch, as has been described in previous posts. If you are still seeing this after updating either SDK (for ASP.NET Core apps) or all EF package versions (for other apps) then please post a project/solution that exhibits the behavior you are seeing.

Problem with the mismatch in the Versions. Issue was fixed when Updated with same Versions.

I'm experiencing the same problem. I create a project, add the MySql.Data.EntityFrameworkCore NuGet package (8.0.11) and add Microsoft.EntityFrameworkCore.Proxies (2.1.1). Even the most simple object (Id + name) causes this exception as soon as I try to use the DBSet.

Note that I'm using MySQL in this particular project.

Exception: Unable to cast object of type 'ConcreteTypeMapping' to type 'Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping'

Simply adding the Microsoft.EntityFrameworkCore.Proxies package is enough to cause the exception; even without calling .UseLazyLoadingProxies()

I tried updating to pre-release (newer) versions of the packages but these seem to be the latest.

Stacktrace:

   at Microsoft.EntityFrameworkCore.Metadata.RelationalPropertyAnnotations.get_ColumnType()
   at MySql.Data.EntityFrameworkCore.Storage.Internal.MySQLTypeMapper.GetColumnType(IProperty property)
   at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapper.FindMapping(IProperty property)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.RelationalTypeMappingConvention.Apply(InternalModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelBuilt(InternalModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelBuilt(InternalModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.Validate()
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass5_0.<GetModel>b__1()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_1(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(IServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_Model()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.CheckState()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Collections.Generic.IEnumerable<TEntity>.GetEnumerator()
   at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
   at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at Repro11704.Program.Main(String[] args) in C:\Users\Rob\Desktop\Repro11704\Repro11704\Program.cs:line 13

Code to repro:

```c#
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace Repro11704
{
class Program
{
static void Main(string[] args)
{
using (var ctx = new MyContext(""))
{
var test = ctx.Foos.ToArray();
}
}
}

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

class MyContext : DbContext
{
    public string ConnectionString { get; private set; }
    public DbSet<Foo> Foos { get; set; }

    public MyContext(string connectionString)
    {
        ConnectionString = connectionString;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);

        optionsBuilder
            .UseMySQL(ConnectionString)
            .UseLazyLoadingProxies();
    }
}

}
```

Commenting out/removing UseLazyLoadingProxies() doesn't help. As soon as I remove the Microsoft.EntityFrameworkCore.Proxies package it works (or: as soon as I add the Microsoft.EntityFrameworkCore.Proxies package the exception is thrown).

Was this page helpful?
0 / 5 - 0 ratings