c# - Counting Database records that meet criteria and displaying in view -
using mvc5 ef6 vs2013
i relatively new mvc , web development in general , wondering best way query database , count number of records meet criteria out of total number of records. in case want count number of active vehicles.
i have used method know display both active , inactive records in table querying database table of vehicles , creating model of active status , counts
the relevant bits model, controller , view below.
model
namespace atas.models { public class activevehicles { public bool active { get; set; } public int vehiclecount { get; set; } } }
controller
public actionresult index() { iqueryable<activevehicles> data = vehicle in db.vehicles group vehicle vehicle.active active select new activevehicles() { active = active.key, vehiclecount = active.count() }; return view(data.tolist()); }
view
<table> <tr> <th> active </th> <th> fleet </th> </tr> @foreach (var item in model) { <tr> <td> @html.displayfor(modelitem => item.active) </td> <td> @item.vehiclecount </td> </tr> } </table>
what want achieve
on view want display there 13 out of 20 vehicles active.
what best way achieve outcome?
edit - found 1 way achieve sure not best practice.
it gets me want sure not efficient. better solutions?
new controller
public actionresult index() { int countallvehicles = (from row in db.vehicles select row).count(); viewbag.allvehicles = countallvehicles; int countactivevehicles = (from row in db.vehicles row.active == true select row).count(); viewbag.activevehicles = countactivevehicles; var percentactive = (double)countactivevehicles / (double)countallvehicles * 100; viewbag.percentactive = percentactive; return view(); }
new view
<div class="col-xs-6 col-sm-6 col-md-12 col-lg-12"> <span class="text">ambulance <span class="pull-right">@viewbag.activevehicles of @viewbag.allvehicles</span> </span> <div class="progress"> <div class="progress-bar bg-color-bluedark" style="width: @viewbag.percentactive%;"></div> </div> </div>
i got curious question , wanted know result myself.
i believe can achieve cross join or better technique can't in linq syntax on generating (sorry that). did create sql query , executed directly on context's db. ensure columns returned match names of properties in model.
code execution , retrieval.
query = @"select count([status]) vehiclecount, t2.active table1 cross join ( select count([status]) active table1 group [status] having [status] = 1 ) t2 group t2.active"; activevehicles data = uow.context.database.sqlquery<activevehicles>(query).firstordefault<activevehicles>();
hopefully or better knowledge in linq can turn query directly linq.
Comments
Post a Comment