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.

Specified cast is not valid on Includes

See original GitHub issue

When 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:closed
  • Created 9 years ago
  • Comments:10 (8 by maintainers)

github_iconTop GitHub Comments

1reaction
bradleylandiscommented, Mar 8, 2015

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.

0reactions
ndenkhacommented, Nov 30, 2016

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 DateTime UpdatedOn { get; set; }
}

public interface ITrackable { DateTime CreatedOn { get; set; }

    DateTime UpdatedOn { get; set; }
}

public class Auditable : Trackable, IAuditable { public string CreatedBy { get; set; }

    public string UpdatedBy { get; set; }
}

public interface IAuditable { string CreatedBy { get; set; }

    string UpdatedBy { get; set; }
}

public class AppUser : Auditable { public int Id { get; set; }

    public string Username { get; set; }    // This can be user's domain ID for internal users and any other ID for external users.

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Email { get; set; }

    public string Title { get; set; }

    public bool IsActive { get; set; }

    public virtual ICollection<Application> Applications { get; set; }

    public virtual ICollection<Role> Roles { get; set; }
    
    public virtual ICollection<Market> Markets { get; set; }

    public AppUser()
    {
        Applications = new List<Application>();
        Roles = new List<Role>();
        Markets = new List<Market>();
    }
}

public class Application : Auditable { public int Id { get; set; }

    public string Name { get; set; }

    public bool IsDeleted { get; set; }

    public virtual ICollection<Role> Roles { get; set; }

    public virtual ICollection<AppUser> AppUsers { get; set; }

    public Application()
    {
        Roles = new List<Role>();
        AppUsers = new List<AppUser>();
    }
}

public class Role : Auditable { public int Id { get; set; }

    public string Name { get; set; }

    public int ApplicationId { get; set; }

    // NOTE: commented out as it creates duplicate EDM relationship.
    //public virtual Application Application { get; set; }

    public virtual ICollection<AppUser> AppUsers { get; set; }

    public virtual ICollection<Scope> Scopes { get; set; } 


    public Role()
    {
        //Application = new Application();
        AppUsers = new List<AppUser>();
        Scopes = new List<Scope>();
    }
}

public class Market { public short Id { get; set; }

    public string Name { get; set; }

    public string State { get; set; }

    public string Region { get; set; }

    public string Timezone { get; set; }

    public byte TimezoneOrder { get; set; }

    public bool IsActive { get; set; }

    public virtual ICollection<AppUser> AppUsers { get; set; }

    public Market()
    {
        AppUsers = new List<AppUser>();
    }
}

// Here are the mapping files. public class ApplicationMap : EntityTypeConfiguration<Application> { public ApplicationMap() { ToTable(“Application”);

        HasKey(x => x.Id);
        Property(x => x.Id).HasColumnName("ApplicationId");

        HasMany(x => x.Roles).WithRequired().HasForeignKey(x => x.ApplicationId);
    }
}

public class AppUserMap : EntityTypeConfiguration<AppUser> { public AppUserMap() { ToTable(“AppUser”);

        HasKey(x => x.Id);
        Property(x => x.Id).HasColumnName("UserId");

        HasMany(x => x.Applications).WithMany(y => y.AppUsers).Map(z =>
        {
            // NOTE: The left table is AppUser, and right table is Application.
            z.MapLeftKey("UserId");
            z.MapRightKey("ApplicationId");
            z.ToTable("UserApplication");
        });

        HasMany(x => x.Roles).WithMany(y => y.AppUsers).Map(z =>
        {
            // NOTE: The left table is AppUser, and right table is Role.
            z.MapLeftKey("UserId");
            z.MapRightKey("RoleId");
            z.ToTable("UserRole");
        });

        HasMany(x => x.Markets).WithMany(y => y.AppUsers).Map(z =>
        {
            // NOTE: The left table is AppUser, and right table is Market.
            z.MapLeftKey("UserId");
            z.MapRightKey("EnterpriseMarketId");
            z.ToTable("UserMarket");
        });

    }
}

public class RoleMap : EntityTypeConfiguration<Role> { public RoleMap() { ToTable(“Role”);

        HasKey(x => x.Id);
        Property(x => x.Id).HasColumnName("RoleId");

    }
}

public class MarketMap : EntityTypeConfiguration<Market> { public MarketMap() { ToTable(“Market”);

        HasKey(x => new {x.Id});
        Property(x => x.Id).HasColumnName("EnterpriseMarketId");
    }
}

public class ScopeMap : EntityTypeConfiguration<Scope> { public ScopeMap() { ToTable(“Scope”);

        HasKey(x => x.Id);
        Property(x => x.Id).HasColumnName("ScopeId");

    }
}

// 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,

CreatedBy varchar(255) not null,
CreatedOn Datetime not null,
UpdatedBy varchar(255) not null,
UpdatedOn DateTime not null

) 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,

CreatedBy varchar(255) not null,
CreatedOn Datetime not null,
UpdatedBy varchar(255) not null,
UpdatedOn DateTime not null,

UNIQUE KEY unique_record (Username, Email)

) 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,

CreatedBy varchar(255) not null,
CreatedOn Datetime not null,
UpdatedBy varchar(255) not null,
UpdatedOn DateTime not null,

index app_index (ApplicationId),
foreign key (ApplicationId) references Application(ApplicationId) on delete cascade

) 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,

CreatedBy varchar(255) not null,
CreatedOn Datetime not null,
UpdatedBy varchar(255) not null,
UpdatedOn DateTime not null,

index app_index (RoleId),
foreign key (RoleId) references Role(RoleId) on delete cascade

) ENGINE=INNODB;

// Association tables

create table IF NOT EXISTS UserApplication ( ApplicationId int not null, UserId int not null,

index app_index (ApplicationId),
index user_index (UserId),
foreign key (ApplicationId) references Application(ApplicationId) on delete cascade,
foreign key (UserId) references AppUser(UserId) on delete cascade,

primary key (ApplicationId, UserId)

) ENGINE=INNODB;

create table IF NOT EXISTS UserMarket ( EnterpriseMarketId smallint not null, UserId int not null,

index market_index (EnterpriseMarketId),
index user_index (UserId),
foreign key (EnterpriseMarketId) references Market(EnterpriseMarketId) on delete cascade,
foreign key (UserId) references AppUser(UserId) on delete cascade,

primary key (EnterpriseMarketId, UserId)

) ENGINE=INNODB;

create table IF NOT EXISTS UserRole ( RoleId int not null, UserId int not null,

index user_index (UserId),
index role_index (RoleId),
foreign key (UserId) references AppUser(UserId) on delete cascade,
foreign key (RoleId) references Role(RoleId) on delete cascade,

primary key (RoleId, UserId)

) ENGINE=INNODB;

Read more comments on GitHub >

github_iconTop 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 >

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