In my app. I am doing some query and deriving results. Then trying to cast/convert them into a specific object type called
BookmarkTag.
Code for generating results -
var bkTags = (
from p in keyWords
select new
{
p.Key,
p.Value
}).Cast<BookmarkTag>().AsEnumerable();
BookmarkTag.cs class -
public class BookmarkTag
{
public string Key { get; set; }
public int Value { get; set; }
}
Another variant I tried -
var bkTags={
from p in keyWords
select new BookmarkTag()
{
p.Key, // throws error in these 2 lines, BookmarkTag class does not implement IEnumerable
p.Value
}).AsEnumerable();
Here keyWords is a variable that contains data in form as -- refer the attached pic link --> pasteboard.co/JEsf72I.png
Error I am getting -
Unable to cast object of type '<>f__AnonymousType1`2[System.String, System.Int32]' to type 'WordCloud.Web.Models.BookmarkTag'.
My 1st guess, BookmarkTag class requires Id field also, since result set is like a List of values and each key-value pair has an index also like {0}, {1}, {2} ..... but, unlikely.
What's the fix? Modification in BookmarkTag model class or query used? Any direct lambda expr. available for achieving the same?
There are more wonders in this world of ours than you can wonder; and it is nice to sometimes wonder at them.
Member
51 Points
307 Posts
Unable to typecast AnonymousType1'2[String, Int] to Models.BookmarkTag [Crucial] --
Dec 11, 2020 04:59 PM|PGChoudhury|LINK
This is the problem scenario -
In my app. I am doing some query and deriving results. Then trying to cast/convert them into a specific object type called
BookmarkTag.
Code for generating results -
BookmarkTag.cs class -
Another variant I tried -
Here keyWords is a variable that contains data in form as -- refer the attached pic link --> pasteboard.co/JEsf72I.png
Error I am getting -
Unable to cast object of type '<>f__AnonymousType1`2[System.String, System.Int32]' to type 'WordCloud.Web.Models.BookmarkTag'.
My 1st guess, BookmarkTag class requires Id field also, since result set is like a List of values and each key-value pair has an index also like {0}, {1}, {2} ..... but, unlikely.
What's the fix? Modification in BookmarkTag model class or query used? Any direct lambda expr. available for achieving the same?
All-Star
52201 Points
23274 Posts
Re: Unable to typecast AnonymousType1'2[String, Int] to Models.BookmarkTag [Crucial] --
Dec 11, 2020 07:56 PM|mgebhard|LINK
Your LINQ projection creates an anonymous type. Create a concrete type.
I think you'll find the official Entity Framework documentation an interesting read as it illustrates the concept.
https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/query-expression-syntax-examples-projection