ravikiran
ravikiran

Reputation: 43

Not able to convert System.Data.Entity.DbSet`1 to type 'System.Data.Entity.DbSet`1

I have created an interface and a class which implements that interface and I am trying to assign the interface reference the class object after querying it form the database

 public interface IErrorCodeMapping : IEntity
 {
     int Id { get; set; }     
     string Errcode { get; set; }
     bool FIBusiness { get; set; }
     bool equity { get; set; }
 }

public class ErrCodeMapping : IErrorCodeMapping
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Key]
    public string Errcode { get; set; }
    public bool FIBusiness { get; set; }
    public bool Equity { get; set; }
}

    IQueryable<IErrorCodeMapping> positions = (DbSet<IErrorCodeMapping>)domainRepository.Query<ErrCodeMapping>();

But I am getting the following error

   InvalidCastException: Unable to cast object of type 
   'System.Data.Entity.DbSet`1[Ex.Domain.Entities.ErrCodeMapping]' to type 
   'System.Data.Entity.DbSet`1[Ex.Domain.Entities.IErrorCodeMapping]'.

Could someone please let me know how can I achieve this casting and what was going wrong. Note: I have tried other casting approaches as well, but none of them seem to work.

Upvotes: 0

Views: 60

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40858

You need to cast the elements inside on the collection, not the collection itself. You can do that with Queryable.Cast<TResult>(IQueryable). In your case, that might look something like this:

IQueryable<IErrorCodeMapping> positions =
    domainRepository.Query<ErrCodeMapping>.Cast<IErrorCodeMapping>();

Upvotes: 1

Related Questions