MVC Linq Queries and MS SQL Server

本文关键字:SQL Server MS and Linq Queries MVC | 更新日期: 2023-09-27 18:05:40

我的问题很简单,如何限制传递给视图的列?

通常,在编写SQL时,SELECT语句将指定所需的列和表,而我使用Linq到目前为止涉及到像这样的查询:

var navigationModel = (from m in db.Navigations where (m.Main == true) orderby m.Position select m);

因此,这将显示下列类中标识的所有列:

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; }
}

因此,上面的Linq查询不是很有效,因为我只想要列Title, Action和Controller。

有人可以告诉我如何过滤数据被传递到一个视图?

任何帮助将不胜感激:-)

MVC Linq Queries and MS SQL Server

创建一个只具有所需属性的新view model:

public class NavigationViewModel
{
    public string Title { get; set; }
    public string Action { get; set; }
}

在Linq中创建一个新模型类的集合:

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
                      };