Reputation: 2483
My question is a fairly straightforward, how to limit columns passed to a View?
Typically when writing SQL a SELECT statement will specify the columns as well as the table(s) required, where as my use of Linq thus far involved inkoing a query like so:
var navigationModel = (from m in db.Navigations where (m.Main == true) orderby m.Position select m);
This would therefore show all columns identified in the following class:
public partial class Navigation
{
public int Id { get; set; }
public string Title { get; set; }
public Nullable<int> Position { get; set; }
public bool Main { get; set; }
public string Action { get; set; }
public string Controller { get; set; }
}
Therefore the above Linq query is not being very efficient as I only want the columns Title, Action and Controller.
Could someone please show me how to filter data being passed to a view?
Any help would be much appreciated :-)
Upvotes: 0
Views: 509
Reputation: 118977
Create a new view model
that only has the properties you need:
public class NavigationViewModel
{
public string Title { get; set; }
public string Action { get; set; }
}
And in your Linq do this to create a collection of your new model class:
var navigationModel = from m in db.Navigations
where (m.Main == true)
orderby m.Position
select new NavigationViewModel //This is the new bit
{
Title = m.Title,
Action = m.Action
};
Upvotes: 5