System.InvalidCastException when adding an entity DBSet<T>.Add()

0

Updating with more information

I am using EF Core 2.0

The entity is:

public class Vehicle
{
 public int Id { get; set; }
 public string TenantId { get; set; }
 public string Make { get; set; }
 public string Model { get; set; }
 public string Year { get; set; }
 }

I have my mapping configuration as,

 public override void Map(EntityTypeBuilder<Vehicle> builder)
 {
      builder.ToTable("Vehicles");
      builder.HasKey(field => field.Id);
      builder.Property(field => field.Make).IsRequired().HasMaxLength(20);
      builder.Property(field => field.Model).IsRequired().HasMaxLength(20);
 }

I configure the entity in DBContext using;

 DataContext.Set<T>(); 

And then if I perform any action against this DbSet it gives this error. Notice the highlighted parts. They are all identical.

System.InvalidCastException occurred HResult=0x80004002 Message= [A]MyProject.Models.Vehicle cannot be cast to [B]MyProject.Models.Vehicle. Type A originates from 'MyProject.Models., Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'D:..\MyProject.Models.dll'. Type B originates from 'MyProject.Models, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'D:..\MyProject.Models.dll'.

The only reference i could find related to above is here. In my case it doesn't seem to be the entity mapping config.

Any help is appreciated.

Update 1:

My Service class accepts type T which defines the entity it's going to work with such as;

public abstract class DomainService<T> : IDomainService where T : class, IEntity 
{ 
    protected DomainService(ApplicationDbContext context) 
    { 
        WorkingSet = context.Set<T>(); 
    } 
} 

The auto property WorkingSet is now correctly setup for the entity T and I can confirm it in debugging. But performing anything with WorkingSet such as WorkingSet.Add(dataentity) gives the error mentioned above.

But, if I hardcode the DbSet in context class like

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
{
    public DbSet<Vehicle> Vehicle { get; set; }
}

It works! If needed I can continue with this option but I would like to avoid hardcoding DbSet in context class.

c#
.net
entity-framework-core
dbcontext
asked on Stack Overflow Nov 18, 2017 by user2058413 • edited Nov 19, 2017 by user2058413

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0