0

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 :-)

1 Answer 1

5

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
                      };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.