Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MVC Linq查询和MS SQL Server_C#_Linq_Sql Server 2012_Asp.net Mvc 5 - Fatal编程技术网

C# MVC Linq查询和MS SQL Server

C# MVC Linq查询和MS SQL Server,c#,linq,sql-server-2012,asp.net-mvc-5,C#,Linq,Sql Server 2012,Asp.net Mvc 5,我的问题相当简单,如何限制传递给视图的列 通常,在编写SQL时,SELECT语句将指定所需的列和表,其中,正如我使用Linq到目前为止所涉及的那样,执行如下查询: var navigationModel = (from m in db.Navigations where (m.Main == true) orderby m.Position select m); 因此,这将显示以下类中标识的所有列: public partial class Navigation { public in

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

通常,在编写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; }
}
公共部分类导航
{
公共int Id{get;set;}
公共字符串标题{get;set;}
公共可空位置{get;set;}
公共布尔主{get;set;}
公共字符串操作{get;set;}
公共字符串控制器{get;set;}
}
因此,上面的Linq查询不是很有效,因为我只需要Title、Action和Controller列

有人能告诉我如何过滤传递给视图的数据吗


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

创建一个新的
视图模型
,该模型只具有您需要的属性:

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

创建一个新的
视图模型
,该模型仅具有所需的属性:

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