【发布时间】:2009-06-10 19:33:10
【问题描述】:
我需要生成几份报告,其中许多只是我的数据库中的实体表。实体可以是任何类型,我并不总是需要整个实体。
我目前的方法是创建一个包含List<List<string>> 类型字段的 ViewModel,它代表我的表格,其中每一行都是一个单元格列表。然后,视图只需要遍历每一行和每一列来创建表。
public class ListReportViewModel
{
public string Title;
public List<string> Headings;
public List<List<string>> Rows;
}
然后我有控制器代码来填充标题和行:
// Get the entities for the report
var tickets = ( from t in _db.Ticket.Include("Company").Include("Caller")
select t );
// Populate the column headings
data.Headings = new List<string>();
data.Headings.Add( "Ticket ID" );
data.Headings.Add( "Company" );
data.Headings.Add( "Caller" );
data.Headings.Add( "Reason for Call" );
// Temporary staging variables
List<List<string>> rows = new List<List<string>>();
List<string> row;
// Populate temporary variables
foreach ( var ticket in tickets )
{
row = new List<string>();
row.Add( ticket.TicketID.ToString() );
row.Add( ticket.Company.Name );
row.Add( ticket.Caller.FirstName + " " + ticket.Caller.LastName );
row.Add( ticket.Subject );
rows.Add( row );
}
// Populate ViewModel field
data.Rows = rows;
虽然这样可行,但似乎效率低下。我遍历整个结果集只是为了填充 ViewModel,然后视图将不得不再次遍历它来构建报告。
我的问题:有没有更简单的方法可以做到这一点?如果我可以让我的 Linq 查询返回一个 IEnumerable<IEnumerable<string>>,那么我可以只使用“data.Rows = tickets”这一行,并且视图本身就能够循环遍历它。
我认为一定有更好的方法来做到这一点,我不知道。
【问题讨论】:
标签: c# asp.net-mvc linq linq-to-entities