Specified cast is not valid on Includes
See original GitHub issueWhen calling this code:
return _db.Trainers
.Include(t => t.TrainerBlobs)
.Include(t => t.Image)
.FirstOrDefault(s => s.Id == id);
It throws the following error:
Additional Information: Specified cast is not valid
I checked the db, and the data is there and correct, so I don’t know what exactly could be causing this to throw. The stacktrace is below:
at Microsoft.Data.Entity.Metadata.ObjectArrayValueReader.ReadValue[T](Int32 index)
at Microsoft.Data.Entity.Relational.Query.OffsetValueReaderDecorator.ReadValue[T](Int32 index)
at Microsoft.Data.Entity.ChangeTracking.SimpleEntityKeyFactory`1.Create(IEntityType entityType, IReadOnlyList`1 properties, IValueReader valueReader)
at Microsoft.Data.Entity.Query.QueryBuffer.IncludeCore(Object entity, INavigation navigation, EntityKey& primaryKey, List`1& bufferedEntities, Func`2& relatedKeyFactory)
at Microsoft.Data.Entity.Query.QueryBuffer.Include(Object entity, IReadOnlyList`1 navigationPath, IReadOnlyList`1 relatedValueReaders, Int32 currentNavigationIndex)
at Microsoft.Data.Entity.Query.QueryBuffer.Include(Object entity, IReadOnlyList`1 navigationPath, IReadOnlyList`1 relatedValueReaders)
at Microsoft.Data.Entity.Relational.Query.QueryMethodProvider.<>c__DisplayClass11_0`1.<_Include>b__2(T qss)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at Microsoft.Data.Entity.Relational.Utilities.EnumerableExtensions.<Finally>d__0`1.MoveNext()
at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at lambda_method(Closure , QueryContext , QuerySourceScope )
at Microsoft.Data.Entity.Query.EntityQueryModelVisitor.<>c__DisplayClass36_0`1.<CreateExecutorLambda>b__1(QueryContext qc)
at Microsoft.Data.Entity.Relational.RelationalDataStore.Query[TResult](QueryModel queryModel)
at Microsoft.Data.Entity.Query.EntityQueryExecutor.ExecuteCollection[T](QueryModel queryModel)
at Microsoft.Data.Entity.Query.EntityQueryExecutor.ExecuteSingle[T](QueryModel queryModel, Boolean _)
at Remotion.Linq.Clauses.StreamedData.StreamedSingleValueInfo.ExecuteSingleQueryModel[T](QueryModel queryModel, IQueryExecutor executor)
at Remotion.Linq.Clauses.StreamedData.StreamedSingleValueInfo.ExecuteQueryModel(QueryModel queryModel, IQueryExecutor executor)
at Remotion.Linq.QueryModel.Execute(IQueryExecutor executor)
at Remotion.Linq.QueryProviderBase.Execute(Expression expression)
at Remotion.Linq.QueryProviderBase.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
at OneOEight.Api.Models.Repositories.TrainerRepository.GetByIdWithIncludes(Guid id) in C:\Users\Alex\Source\Freelance\OneOEight\OneOEight.Api\src\OneOEight.Api\Models\Repositories\TrainerRepository.cs:line 55
at OneOEight.Api.Areas.V1.Controllers.TrainersController.Get(String id) in C:\Users\Alex\Source\Freelance\OneOEight\OneOEight.Api\src\OneOEight.Api\Areas\V1\TrainersController.cs:line 81
Issue Analytics
- State:
- Created 9 years ago
- Comments:10 (8 by maintainers)
Top Results From Across the Web
Specified cast is not valid?
this is the answer, you're selecting the wrong columns, if your table has an identity table then you're selecting the id with 0...
Read more >[Solved] Specified cast is not valid C# - CodeProject
How to solve above error any one give me some ideas. What I have tried: System.InvalidCastException: 'Specified cast is not valid.' Posted ...
Read more >Specified Cast Is Not Valid – Understanding the Error
The specified cast is not valid error occurs when you try to cast an object or variable of a data type that the...
Read more >System.InvalidCastException: Specified Cast is not valid - ...
When you view your ASP.NET page in the browser, you may receive the following error message: Specified cast is not valid. Description: An...
Read more >Specified cast is not valid. Xamarin.Forms
Hi Everyone ! i have this project in which i need to Retrieve a list of data, when i click the Retrieve Button,...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Did you make sure the types in your database match your model? Usually this comes from having something like int in your model and bigint in your database. In that case, changing your model to long fixes it.
In your case it would be on one of the included models. I’m especially suspicious of this since you refer to blobs and images. What type are you using in the database for those fields and what do your models look like?
A more specific error message would be nice here though.
Hi guys, I’m having this issue with EF 6.1.3 and it only happens when I include any 3rd Include, i.e. I can get a single or 2 navigation props in any combination fine. I’m running against MySQL 5.7 AWS RDS, and here are my models and tables.
// If I take any one of the includes I get the user object back correctly with only those two navigation props populated, the moment I add any 3rd include I get the error.
Please advise.
var existingUser = Users.Include(x => x.Applications) .Include(x => x.Roles) .Include(x => x.Markets) .FirstOrDefault(x => x.Id == user.Id);
public abstract class Trackable : ITrackable { public DateTime CreatedOn { get; set; }
public interface ITrackable { DateTime CreatedOn { get; set; }
public class Auditable : Trackable, IAuditable { public string CreatedBy { get; set; }
public interface IAuditable { string CreatedBy { get; set; }
public class AppUser : Auditable { public int Id { get; set; }
public class Application : Auditable { public int Id { get; set; }
public class Role : Auditable { public int Id { get; set; }
public class Market { public short Id { get; set; }
// Here are the mapping files. public class ApplicationMap : EntityTypeConfiguration<Application> { public ApplicationMap() { ToTable(“Application”);
public class AppUserMap : EntityTypeConfiguration<AppUser> { public AppUserMap() { ToTable(“AppUser”);
public class RoleMap : EntityTypeConfiguration<Role> { public RoleMap() { ToTable(“Role”);
public class MarketMap : EntityTypeConfiguration<Market> { public MarketMap() { ToTable(“Market”);
public class ScopeMap : EntityTypeConfiguration<Scope> { public ScopeMap() { ToTable(“Scope”);
// Here are the tables.
create table IF NOT EXISTS Application ( ApplicationId int not null auto_increment primary key, Name varchar(255) not null, IsDeleted bool not null default false,
) ENGINE=INNODB;
create table IF NOT EXISTS AppUser ( UserId int not null auto_increment primary key, Username varchar(255) not null, FirstName varchar(255) not null, LastName varchar(255) not null, Email varchar(255) not null, Title varchar(255) null, IsActive bool not null default false,
) ENGINE=INNODB;
create table IF NOT EXISTS Market ( EnterpriseMarketId smallint not null primary key, Name varchar(255) not null, State varchar(2) not null, Region varchar(255) not null, Timezone varchar(25) not null, TimezoneOrder tinyint not null, IsActive tinyint(1) not null ) ENGINE=INNODB;
create table IF NOT EXISTS Role ( RoleId int not null auto_increment primary key, Name varchar(255) not null, ApplicationId int not null,
) ENGINE=INNODB;
create table IF NOT EXISTS Scope ( ScopeId int not null auto_increment primary key, Name varchar(255) not null, RoleId int not null, Document JSON,
) ENGINE=INNODB;
// Association tables
create table IF NOT EXISTS UserApplication ( ApplicationId int not null, UserId int not null,
) ENGINE=INNODB;
create table IF NOT EXISTS UserMarket ( EnterpriseMarketId smallint not null, UserId int not null,
) ENGINE=INNODB;
create table IF NOT EXISTS UserRole ( RoleId int not null, UserId int not null,
) ENGINE=INNODB;