2013-05-06 91 views
0

我傳遞評價模型研究使用重定向到行動結果採取行動的數量。在結果動作控制器我想 執行LINQ語句中使用存儲庫檢索的行數和任何值posted.for例如Linq的語句返回行

number of rows = Select * 
       from table or model 
       where SmokesInHouse = SmokesInHouse And 
         SmokesInCar = SmokesInCar And 
         SmokesAtWork = SmokesAtWork' 
public class SampleController : Controller 
{ 
    private IEnvRepository repository; 

    public SampleController(IEnvRepository assesmentRepository) 
    { 
     repository = assesmentRepository; 
    } 

    [HttpPost] 
    public ActionResult SmokingEnvironments(Assessment a) 
    { 
     if (ModelState.IsValid) 

      return RedirectToAction("Results", new { SmokesInHouse =SmokesInHouse,  SmokesInCar = a.SmokesInCar, SmokesAtWork=a.SmokesAtWork }); 
     } 
     return View(a); 
    } 

    [HttpGet] 
    public ActionResult Results() 
    { 
     return View(); 
    } 
} 

回答

3

您需要更新Results行動接受Assessment模型即

[HttpGet] 
public ActionResult Results(AssessmentModel assessment) 
{ 
    int rows = myTable.Where(x => x.SmokesInHouse == assessment.SmokesInHouse && 
            x.SmokesInCar == assessment.SmokesInCar && 
            x.SmokesAtWork == assessment.SmokesInWork).Count(); 
    return View(rows); 
} 
+0

'X.Where(P).Count之間()'相當於'X.Count(P)'。 – 2013-05-06 18:51:29

1

請嘗試以下方法得到你的模型吸菸者總數:

int totalSmokers = model.Where(x => x.SmokesInHouse && x.SmokesInCar && x.SmokesAtWork).Count(); 

如果從數據庫表中查詢,您將使用相同的where子句。

+0

OP表示條件是「AND」而不是「OR」。 – James 2013-05-06 14:49:59

0

有一個過載的Count method需要一個謂詞。有了它的查詢可以簡化爲這樣的:

int totalSmokers = xs.Count(x => 
    x.SmokesInHouse == a.SmokesInHouse && 
    x.SmokesInCar == a.SmokesInCar && 
    x.SmokesAtWork == a.SmokesAtWork); 

我假設這是將在服務器上執行一個IQueryable,它可能沒有什麼區別。但是,如果它是一個IEnumerable,它可能會對大型序列產生影響。