Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast object of type '<>f__AnonymousType5`6

I have two list. from one i want two select few data and then save that data to another list.

var ikj = Model.EmployeeInformationList
     .Select(m => new { m.GEmployeeGenInfoID, m.strDesignationName, m.strEmpOldCardNo, m.StrEmpID, m.GFactoryID, m.StrEmpName })
    .Distinct().ToList();


List<HolidayAlwEmployeeInfo> targetList = new List<HolidayAlwEmployeeInfo>(ikj.Cast<HolidayAlwEmployeeInfo>());

Model.HolidayAlwEmployeeInfoList = targetList;

but I'm getting this error

Unable to cast object of type '<>f__AnonymousType5`6[System.Guid,System.String,System.String,System.String,System.Guid,System.String]' to type 'FactoryProduct.Entities.Payroll.HolidayAlwEmployeeInfo'

like image 984
Gin Uchiha Avatar asked Dec 19 '22 03:12

Gin Uchiha


1 Answers

You are trying to cast instance of anonymous type that you created by calling new { m.GEmployeeGenInfoID, m.strDesignationName, m.strEmpOldCardNo, m.StrEmpID, m.GFactoryID, m.StrEmpName } to the type HolidayAlwEmployeeInfo, you can't do that.

Rather, you need to rewrite the first line like this:

var ikj = Model.EmployeeInformationList
               .Select(m => new HolidayAlwEmployeeInfo(
                                m.GEmployeeGenInfoID,
                                m.strDesignationName,
                                m.strEmpOldCardNo,
                                m.StrEmpID,
                                m.GFactoryID,
                                m.StrEmpName ))
               .Distinct()
               .ToList();

and make sure that HolidayAlwEmployeeInfo class has appropriate constructor to take all of the parameters m.GEmployeeGenInfoID, m.strDesignationName, m.strEmpOldCardNo, m.StrEmpID, m.GFactoryID, m.StrEmpName

Alternatively (as Stephen Muecke mentioned in his comment), you can instantiate HolidayAlwEmployeeInfo with a simple constructor and assign properties/fields in the initializer, like this:

var ikj = Model.EmployeeInformationList
               .Select(m => new HolidayAlwEmployeeInfo()
                            {
                                GEmployeeGenInfoID=m.GEmployeeGenInfoID,
                                strDesignationName=m.strDesignationName,
                                strEmpOldCardNo=m.strEmpOldCardNo,
                                StrEmpID=m.StrEmpID,
                                GFactoryID=m.GFactoryID,
                                StrEmpName=m.StrEmpName
                            })
               .Distinct()
               .ToList();
like image 107
Denis Yarkovoy Avatar answered Dec 21 '22 18:12

Denis Yarkovoy