2

使用するEFデータモデルを備えた単純なデータベースがあります。

私のテーブルは次のようになります。

顧客テーブル

  • 顧客ID
  • 顧客名

注文表

  • OrderId
  • CustomerID FK
  • 注文日

ヘルパークラスを使用してモデルをクエリしています。このクラスでは、次のクエリがあります。

public static List<object> GetCustomerOrdersCount()
{
    using (OrdersDbEntities context = new OrdersDbEntities())
    {
        return context.Customers.Select(
            c => new
            {
                CustId = c.CustomerId,
                CustName = c.CustomerName,
                OrdersCount = c.Orders.Count
            }).ToList<object>();
    }
}

このメソッドで使用できる唯一の戻りタイプは、List<object>

そして最後に私の質問は、このクエリから受け取ったデータをどのように使用するかです。

値を読み取ることができる唯一の方法は、リフレクションによるものです。

List<object> custs = Dal.GetCustomerOrdersCount();

foreach (var customer in custs)
{
   var properties = customer.GetType().GetProperties();

   foreach (var data in properties)
   {
      var value = data.GetValue(custs[0], null);
   }
}

これを行うためのより良い方法があるのだろうか。

4

3 に答える 3

2
public class MiniCustomerDto
{
  public int CustomerId{get;set;}
  public String CustomerName{get;set;}
  public int OrdersCount{get;set;}
}

public static List<MiniCustomerDto> GetCustomerOrdersCount()
{
        using (OrdersDbEntities context = new OrdersDbEntities())
        {
            return context.Customers.Select(c => new MiniCustomerDto
            {
                CustId = c.CustomerId,
                CustName = c.CustomerName,
                OrdersCount = c.Orders.Count
            }).ToList();
        }
}

匿名型を返すメソッドを作成できないクラスを使用する必要があります。
これはベストプラクティスのチェック
です。メソッドから匿名型を返す方法はありますか?
匿名タイプの結果を返しますか?
ちなみにDtoはDataTransferObjectの略です

于 2012-04-18T20:08:15.290 に答える
1

私が見る問題は、あなたが匿名タイプを選択しているということです、あなたはそうすることができません:

public static List<object> GetCustomerOrdersCount()
{
        using (OrdersDbEntities context = new OrdersDbEntities())
        {
            return context.Customers.Select().ToList<Customer>();
        }
}

Customerこれにより、特定のメンバーのみを含む匿名タイプではなく、完全なエンティティが返されます。

編集

遅延読み込みに関する会話に関する根本的な問題が、実際に注文を読み込むことなく、特定の顧客の注文数をカウントすることである場合は、次のようにします。

public class CustomerWithOrderCount
{
    public CustomerWithOrderCount(Customer c, int OrderCount) 
    { 
        Customer = c; 
        this.OrderCount = OrderCount;
    }
    public Customer { get; set; }
    public int OrderCount { get; set; }
}

public static List<object> GetCustomerOrdersCount()
{
        using (OrdersDbEntities context = new OrdersDbEntities())
        {
            return context.Customers.Select(
                c => new CustomerWithOrderCount(c, c.Orders.Count())
                             .ToList();
        }
}
于 2012-04-18T19:38:31.337 に答える
0
 List<tbl_GameConfig> gameConfig = new List<tbl_GameConfig>();
 using (Entities con = new Entities())
  {
       gameConfig = con.tbl_GameConfig.Where(p => p.fk_GameTypeId == gameTypeId).ToList<tbl_GameConfig>();
  }       
于 2013-01-24T10:26:18.363 に答える