During my web application development in asp.net I am facing following error,
No coercion operator is defined between types <>f__AnonymousType01[System.Collections.Generic.IEnumerable1[clsDAL.AnsType]]’ and ‘clsDAL.AnsType’.
This error accruing when I am fetching data from Database using LInqToSQL. The function in which this error accruing is as below.
public static IList<AnsType> GetAnswer(int id)
{
var TempAns = GlobalClass.DBContext.tbQueAns.Where(s => s.QueId == id).Select(s => s.AnsVal).ToList();
var TAns = GlobalClass.DBContext.tbQueOptions.Where(s=>s.QueId == id).Join(GlobalClass.DBContext.tbQueAns, x => x.OptionId, s => s.AnsVal, (a, b) => new { ans = a.OptionVal });
List<AnsType> Ans = TAns.Cast<AnsType>().ToList();
return Ans;
}
And the type of AnsType is as below…
public class AnsType
{
public string AnsVal { get; set; }
}
I am didn’t getting understand what is exactly going on, I had also try to search this problem on Google but I didn’t getting answer.
And I also want to know the reasons of accruing this error.
This should work:
The reason it happens, is because you’re trying to
implicitlycast anonymous type and you cannot do that.Alliteratively, you can specify a conversion operator like this:
and then use it like this:
List<AnsType> Ans = TAns.Select(x=>x.ans).Cast<AnsType>().ToList();