2
I got the following model
:
public class Crm_Analise
{
[Key]
public int id { get; set; }
public string cod_item_CRM { get; set; }
public string TAG { get; set; }
public string data_creat { get; set; }
public string modelo { get; set; }
public int cliente_CRM { get; set; }
}
Via scaffolding managed the controller and the views.
I changed the View Index
for:
<table class="table">
<tr>
<th>
@Html.ActionLink("TAG", "Index")
</th>
<th>
@Html.ActionLink("ATUALIZAÇÃO", "Index")
</th>
<th>
@Html.ActionLink("RELATÓRIOS", "Index")
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.TAG)
</td>
<td>
@Html.DisplayFor(modelItem => item.data_creat)
</td>
<td>
@Html.DisplayFor(modelItem => item.modelo)
</td>
<td>
@Html.ActionLink("Visualizar", "Details")
</td>
</tr>
}
</table>
So I wanted to group by TAG
, being MAX(data_creat)
and COUNT(modelo)
.
If it were via SQL, I would:
SELECT TAG, MAX(data_creat) AS 'ATUALIZAÇÃO', COUNT(modelo) AS 'RELATÓRIOS'
FROM Crm_Analise
WHERE cliente_CRM = @cliente_CRM
GROUP BY TAG
Then in the controller done:
// GET: Crm_Analise
[Authorize]
public async Task<ActionResult> Index()
{
if (Session["cod_cli"] != null)
{
int cod_cli = Convert.ToInt32(Session["cod_cli"]);
var query = from s in db.Crm_Analise
select s;
query = query.Where(s => s.cliente_CRM == cod_cli);
return View(await query.ToListAsync());
}
else
{
return RedirectToAction("Login", "Account");
}
}
But how do I apply the MAX
, COUNT
and the GROUP BY
?
Update ref. the @Maniero response:
When trying to execute according to the answer, the error was generated:
Update ref. to @LINQ comments:
I changed the variable of Count
for a variable of type int
:
How do you intend to apply a
Count
passing astring
? You want to count the models that are not null?– Jéf Bueno
@Linq, correct me if I’m wrong please, no sql, I can count, even if I’m the type
Varchar
Right? Why not here? I changed it to an INT variable and still the error continues.– Thomas Erich Pimentel
No, you’re confusing things. You need to know what wants to count. The
Count
receives a predicate and not an element. And in SQL there is no "count even if it is varchar", if you put a column in Count it will be validated if that column is null.– Jéf Bueno