Question

I have an aggregated data view in an MVC project which displays the totals per month broken down by audit status. The controller code sets this up using a simple LINQ projection into an anonymous object like this:

From audits In db.Audits
Group By key = audits.DateCreated.Value.Month Into g = Group
Select New With {
    .Month = key,
    .Assigned = g.Sum(AuditsWithStatus(AuditStatus.Issued)),
    .Unassigned = g.Sum(AuditsWithStatus(AuditStatus.Pending)),
    .Closed = g.Sum(AuditsWithStatus(AuditStatus.Closed)),
    .Cancelled = g.Sum(AuditsWithStatus(AuditStatus.Cancelled))
}

I know this is one of the big advantages of LINQ (using anonymous types), but I don't like losing the strong typing in the view (ie @ModelType SomeStrongType). Is there any general advice on this? Articles, blogs, or other places that deal with the issue and when to use which?

Was it helpful?

Solution

You cannot do anything with anonymous types outside of the scope of your method. You cannot return them to your view for example. In those cases you have to use a known type.

I use anonymous types when I am selecting data that I am then processing in another way. For example, selecting some bespoke data out of 1 source using Linq, and putting to put into another source.

If you are returning aggregate data such as an IEnumerable<IGrouping<TKey, TValue>> and TKey and TValue are anonymous types (you can group by anonymous types if you want); then you would not want to create 2 classes for TKey and TValue, where TKey has an overridden Equals and GetHashCode so you can group by it. And then do nothing more than read some values from it and throw it away, never to be re-used.

TLDR; use them when there is no need to create a known type to store your results. If you need to pass your results to somewhere outside the scope of the method, then you will need a type.

OTHER TIPS

General advice is simple: always create dedicated viewmodel type for your views. In your case it would be pretty simple, containing exactly the properties you have in you anonymous class.

I understand that it seems like an unneeded overhead, but it'll make your code more readable and verifiable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top