0

我正在使用重定向到操作将评估模型传递给结果操作。在结果操作控制器中,我想执行一个 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();
    }
}
4

3 回答 3

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);
}
于 2013-05-06T14:40:48.063 回答
1

尝试以下方法来获取模型中的吸烟者总数:

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

如果从数据库表中查询,您将使用相同的 where 子句。

于 2013-05-06T14:46:45.710 回答
0

有一个采用谓词的Count 方法的重载。有了它,查询可以简化为:

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

我假设这是一个将在服务器上执行的 IQueryable,它可能没有什么区别。但如果它是一个 IEnumerable,它可能会对大序列产生影响。

于 2013-05-06T22:22:32.593 回答