【问题标题】:MVC Linq Queries and MS SQL ServerMVC Linq 查询和 MS SQL Server
【发布时间】:2014-05-29 14:06:50
【问题描述】:

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

通常,在编写 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 列。

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

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

【问题讨论】:

    标签: c# linq sql-server-2012 asp.net-mvc-5


    【解决方案1】:

    创建一个新的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
                          };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      相关资源
      最近更新 更多