簡體   English   中英

MVC Linq查詢和MS SQL Server

[英]MVC Linq Queries and MS SQL Server

我的問題很簡單,如何限制傳遞給View的列?

通常,在編寫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查詢不是很有效,因為我只想要標題,操作和控制器列。

有人可以告訴我如何過濾傳遞到視圖的數據嗎?

任何幫助將非常感激 :-)

創建一個僅具有所需屬性的新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
                      };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM