简体   繁体   English

ASP.NET MVC2:来自join的IQueryable

[英]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? 那么我需要声明而不是var才能访问匿名类型? I've tried using LOGGER, which works, however it obviously does not give me access to TESTCASE. 我尝试过使用LOGGER,但它显然不能让我访问TESTCASE。

I'm looking for something like: 我正在寻找类似的东西:

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

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. 这样您就可以访问所有内容,因为您使用的类型不再是匿名类型。

I won't even get into whether you should be doing Linq within the controller. 我甚至不知道你是否应该在控制器内做Linq。 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};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM