データベースをそのままにして、アプリケーションでレポート操作を実行します。以下で行った方法と同様に、Northwind データベースを使用して Customers を Orders に結合し、Reg Number の代わりに Order Id を使用します。
2 つのクラスを作成します。
public class Customer
{
public string Name { get; set; }
public IEnumerable<Order> Orders { get; set; }
}
public class Order
{
public int Id { get; set; }
}
Customers と Orders のデータ テーブルと外部キーのテーブル間の関係を使用して、データのデータセットを作成します。型指定されたデータセットを使用してアダプターの作成を自動化しましたが、手動で作成する場合も同じ原則が適用されます。
データを取得して配置する ViewModel クラスを作成します。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SO_StringAggregate
{
public class ViewModel
{
public ViewModel()
{
// populate the data set
var dataSet = new NorthwindDataSet();
using (var customersAdp = new NorthwindDataSetTableAdapters.CustomersTableAdapter())
using (var ordersAdp = new NorthwindDataSetTableAdapters.OrdersTableAdapter())
{
customersAdp.Fill(dataSet.Customers);
ordersAdp.Fill(dataSet.Orders);
}
// populate your domain objects
var customers = dataSet.Customers.ToArray().Select(cust => new Customer
{
Name = cust.Company_Name,
Orders = cust.GetOrdersRows().Select(order => new Order { Id = order.Order_ID })
});
this.Customers = customers;
// build the report
StringBuilder report = new StringBuilder();
string formatString = "{0,-30}|{1}";
report.Append(string.Format(formatString, "Name", "Order Ids"));
report.Append(Environment.NewLine);
Customers.ToList().ForEach(cust => report.AppendLine(string.Format(
formatString,
cust.Name,
string.Join(",", cust.Orders.Select(o => o.Id).ToArray()))
));
// display the report
Report = report.ToString();
}
public IEnumerable<Customer> Customers { get; set; }
public string Report { get; set; }
}
}
その後、Report プロパティにバインドされたビューにデータを表示できます。
<Window x:Class="SO_StringAggregate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox FontFamily="Consolas" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Text="{Binding Report}" />
</Grid>
</Window>