Chris
Chris

Reputation: 11

ASP.NET MVC2: IQueryable from join

In my controller class I have to join two tables:

var query = from logger in database.LOGGERs
                        join testcase in database.TESTCASEs on logger.TCID equals testcase.TCID select new {logger, testcase};

In the view I'm trying to call the values, for example:

 <% foreach (var testCase in Model.SearchResults)

     <td width="200"title="<%= (testCase.SCRIPTNAME %>"

This leads to the error:

Unable to cast object of type '<>f__AnonymousType1`2[TestAutomationService.Models.LOGGER,TestAutomationService.Models.TESTCASE]' to type 'TestAutomationService.Models.LOGGER'.

So what do I have to declare instead of var to be access the anonymous-type? I've tried using LOGGER, which works, however it obviously does not give me access to TESTCASE.

I'm looking for something like:

foreach (IQuerable<{LOGGER, TESTCASE}> testCase in Model.SearchResults) 
...

Upvotes: 1

Views: 748

Answers (2)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

I won't even get into whether you should be doing Linq within the controller. Yes, I know most samples show that, but it's not good practice.

However, to solve your problem, you will have to create a data transfer object. Something like:

class LoggerTestcase {
    public Logger Logger {get;set;}
    public Testcase Testcase {get;set;}
}

var query = from logger in database.LOGGERs
    join testcase in database.TESTCASEs on logger.TCID equals 
    testcase.TCID select new LoggerTestcase {Logger = logger, Testcase = testcase};

Upvotes: 0

Brian Ball
Brian Ball

Reputation: 12596

This is the downside of anonymous types. Once you're outside of the scope that it was created in, there isn't an easy way to access its members without using reflection.

My suggestion would be to create another class that has the information the view needs (a view model) and fill it in with the results of the query. That way you will be able to access everything since the type you are working with is no longer an anonymous type.

Upvotes: 4

Related Questions