2013-05-06 105 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,它可能会对大型序列产生影响。