英文:
Not able to convert System.Data.Entity.DbSet`1 to type 'System.Data.Entity.DbSet`1
问题
我已经创建了一个接口和一个实现了该接口的类,并且我正在尝试从数据库中查询后将接口引用分配给类对象。
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>();
但我得到了以下错误:
InvalidCastException: 无法将类型为 'System.Data.Entity.DbSet`1[Ex.Domain.Entities.ErrCodeMapping]' 的对象强制转换为类型 'System.Data.Entity.DbSet`1[Ex.Domain.Entities.IErrorCodeMapping]'。
请问有人能告诉我如何执行此强制转换以及出了什么问题。
**注意**: 我也尝试了其他转换方法,但似乎都不起作用。
请注意,这个错误是由于你尝试将一个实现类的对象转换为接口的对象,这是不允许的。要解决这个问题,你可以考虑使用LINQ进行投影,将结果映射到接口类型,而不是尝试进行强制转换。
英文:
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.
答案1
得分: 1
需要将集合内部的元素进行类型转换,而不是集合本身。您可以使用Queryable.Cast<TResult>(IQueryable)
来实现。在您的情况下,代码可能如下所示:
IQueryable<IErrorCodeMapping> positions =
domainRepository.Query<ErrCodeMapping>.Cast<IErrorCodeMapping>();
英文:
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>();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论