这篇文章有很多可能的重复.但我尝试了大多数,不幸的是我的错误仍然发生.
错误是:错误1无法将类型隐式转换
'System.Collections.Generic.List<Report.Business.ViewModels.InvoiceMaster>'为'System.Collections.Generic.IList<ICSNew.Data.InvoiceHD>'.存在显式转换(您是否错过了演员?)
public IList<InvoiceHD> GetAllInvoiceMasterDetailsByInvoiceId(int InvoiceId)
{
var dbMstDtl = ireportrepository.GetAllInvoiceMasterDetailsByInvoiceId(InvoiceId);
var MstDtl = from mst in dbMstDtl
select new Report.Business.ViewModels.InvoiceMaster
{
ModifiedDate = mst.ModifiedDate,
SubTotal = Convert.ToDecimal(mst.SubTotal),
TotalDiscount = Convert.ToDecimal(mst.TotalDiscount),
VAT = Convert.ToDecimal(mst.VAT),
NBT = Convert.ToDecimal(mst.NBT),
AmtAfterDiscount = Convert.ToDecimal(mst.AmtAfterDiscount)
};
return MstDtl.ToList();
}
Run Code Online (Sandbox Code Playgroud)
在一些帖子中,我看到这个东西在使用 return MstDtl.AsEnumerable().ToList();
但在我的情况下它也没有工作(得到错误)
Jon*_*eet 11
假设InvoiceMaster派生自或实现InvoiceHD,并且您正在使用C#4和.NET 4或更高版本,则可以使用泛型方差:
return MstDtl.ToList<InvoiceHD>();
Run Code Online (Sandbox Code Playgroud)
它使用的事实,一个IEnumerable<InvoiceMaster>是IEnumerable<InvoiceHD>因为IEnumerable<T>是协变在T.
解决它的另一种方法是更改MstDtl使用显式类型的声明:
IEnumerable<InvoiceMaster> MstDtl = ...;
Run Code Online (Sandbox Code Playgroud)
(我还建议遵循常规的C#命名,其中局部变量以小写字母开头,但这是另一回事.)