2016-04-14 12 views
0

私はこのLINQクエリLinqクエリでモデルプロパティを使用するにはどうすればよいですか?

var sales=db.Customers 
    .GroupBy 
    .Select(c=> new MyModel 
    { 
     count1=c.where(someCondition).Count(), 
     count2=c.where(otherCondition).Count(), 
     finalCount=count2-count1 
    }); 

がLINQでいる可能性がありますか? どうすればこのような問題を解決できますか?

+2

あなたはGROUPBY句を提供する必要があります。 – HimBromBeere

+0

あなたはあなたの問題を言及していません –

+1

@HimBromBeere彼はしませんでしたが、この質問では重要ではありません:それは 'Select'節に関するものです。 –

答えて

1

をプロパティ初期化後のコード:

var sales=db.Customers.GroupBy(...).Select(c => 
{ 
    var model new MyModel{ 
     count1=c.Count(), 
     count2=c.Count() 
    } 
    model.finalCount = model.count1 - model.count2 

    return model; 
}); 

この場合、私はちょうどc mymodelというクラスの読み取り専用プロパティreate:

public class MyModel 
{ 
    public int FinalCount => count1 - count2; 
} 

をそしてだけで必要なフィールドを初期化:

var sales=db.Customers.GroupBy(...).Select(c => new MyModel 
{ 
    count1=c.Count(), 
    count2=c.Count() 
}); 

FinalCountすることはあなたのために自動的に計算されます。

+1

が役に立ちました。本当に助けになりました –

3

あなたは、まずあなたが二Selectに突出匿名型を選択することができます

var sales = db.Customers 
    .GroupBy(...) 
    .Select(g => new 
    { 
     count1 = g.Where(condition).Count(), 
     count2 = g.Where(condition).Count() 
    }) 
    .Select{x => new MyModel 
    { 
     count1 = x.count1, 
     count2 = x.count2, 
     finalCount = x.count2 - x.count1 
    }); 
+0

EFは2つの「選択」チェーンを処理できません。それ以外の場合、私はここで 'AsEnumerable'が何をしているのか理解していません。 –

+1

@AlexZhukovskiy:すべてがSQLに変換されますが、オブジェクトの初期化はSQLに変換できません。 'AsEnumerable'はクエリを実行し、オブジェクトの初期化を' Linq-To-Objects'で行います。したがって、AsEnumerableを使用する前にフィルタリングすることは良いことです。そうでなければ、テーブル全体をメモリにストリームします(または 'GroupBy'の結果)。 –

+0

@TimSchmelter、私はあなたの2番目のクエリで 'AsEnumerable'は必要ないと思います。 EFは、DTOとも呼ばれる 'MyModel'のようなカスタムクラスでクエリをプロジェクトすることをサポートしています – octavioccl

4

ありませんが、しかし、あなたは無名ブロックを使用することができます:私はあなたに適切だけの場所を理解していれば

var sales=db.Customers.GroupBy(...).Select{c=> 
{ 
    int count1 = c.Count(condition1); 
    int count2 = c.Count(condition2); 

    return new MyModel{ 
     count1=count1, 
     count2=count2, 
     finalCount= count2 - count1 
    } 
}); 
+2

'db'はOPがEFを使用していることを示します。その場合、ステートメント本体のラムダ式を式ツリーに変換することができないので、selectを使用することはできません。 – octavioccl

1

ます。また、この使用let句を行うことができます。

var sales=from c in db.Customers 
      group c by c.SomeColumn into g 
      let Count1= =g.Count(someCondition) 
      let Count2=g.Count(otherCondition) 
      select new MyModel 
       { 
        count1=Count1, 
        count2=Count2, 
        finalCount=Count1-Count2 
       }; 

同じ使用方法構文:

var sales=db.Customers 
    .GroupBy(c=>c.SomeColumn) 
    .Select(g=>new 
    { 
     Count1=g.Count(someCondition), 
     Count2=g.Count(otherCondition) 
    }) 
    .Select(c=> new MyModel 
    { 
     count1=c.Count1, 
     count2=c.Count2, 
     finalCount=c.Count1-c.Count2 
    }); 
関連する問題