Nuru Salihu
Nuru Salihu

Reputation: 4928

How to cast linq query to an object IEnumerable module class type?

I am using a linq query like below

var result = from posts in repository.JobPosts
                      orderby posts.PostDate descending
                       select posts;

I have a property class JobPost with the same column names and number of columns just like the Table from the query above. I created another module class of with a method of the type JobPost class like below

 public class MainPageModel
 {
        public IEnumerable<JobPost> jobPost { get; set; }
        public SearchTerms searchTerms { get; set; }
 }

My JobPost is another module/propery class with equal rows as the JobPosts table above. I am trying to cast my query result to my module directly considering both are of the same columns. I modified my query to

IEnumerable<JobPost> res =(IEnumerable<JobPost>)
                           (from posts in repository.JobPosts
                            orderby posts.PostDate descending
                            select posts) ;

My linq above returned the row quesry

SELECT 
    *
    FROM [dbo].[JobPosts] AS [Extent1]
    ORDER BY [Extent1].[Id] ASC

Is there any way i can return the result of my query (that is the rows) and cast them to my IEnumerable class considering they are of equal columns.

Any help would be appreciated.

EDIT

I plan to populate my class with the resulting query like below.

 MainPageModel model = new MainPageModel
        {
            jobPost = res,
            searchTerms = search
        };

Upvotes: 2

Views: 3366

Answers (2)

David P
David P

Reputation: 2083

You can query database directly using ExecuteQuery:

IEnumerable<JobPost> res = repository.ExecuteQuery<JobPost>("SELECT * FROM JobPosts ORDER BY Id");

Upvotes: 0

Jamiec
Jamiec

Reputation: 136094

Just because they have the same properties, it does not mean you can cast from one to the other. At very least you must map these properties explicitly:

IEnumerable<JobPost> res =(IEnumerable<JobPost>)
                       (from posts in repository.JobPosts
                        orderby posts.PostDate descending
                        select new JobPost{
                           Field1 = posts.Field1,
                           Field2 = posts.Field2,
                        }) ;

You may like to look at AutoMapper too, as it simplifies (with some overhead!) this sort of task

Upvotes: 5

Related Questions