C# MVC Linq查询和MS SQL Server
我的问题相当简单,如何限制传递给视图的列 通常,在编写SQL时,SELECT语句将指定所需的列和表,其中,正如我使用Linq到目前为止所涉及的那样,执行如下查询: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
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
};