簡體   English   中英

如何傳遞從多個表獲取數據的LINQ語句到模型以填充視圖?

[英]How to pass a LINQ statement getting data from multiple tables to a model to populate a View?

我非常想針對我做錯的事情指出正確的方向。 我試圖從數據庫中的多個表中提取數據,然后計划用該數據填充視圖中的表。 我以前是從單個表完成此操作的,沒有問題,但是我在LINQ語句中如何使用聯接進行絆腳石。

這是我試圖獲取相關數據的控制器:

public ActionResult PurchaseHistory()
    {
        //Get White Label ID to filter results
        var whiteLabelId = new WhiteLabelHelper().GetWhiteLabelId();

        PurchaseHistoryModel model = new PurchaseHistoryModel();



        model = from pc in db.PurchasedCards
                              join c in db.Cards on pc.CardId equals c.CardId
                              join u in db.Users on pc.UserId equals u.UserId
                              join g in db.FundraisingGroups on pc.GroupId equals g.GroupId
                              where c.WhiteLabelId == whiteLabelId
                              select new PurchaseHistoryModel { Card = c.Name, User = u.Name, Group = g.Name, Proceeds = pc.NPOProceeds };



        return View(model);
    }

當我意識到不確定如何將所有這些都扔到匿名類型列表中時,這是我開始創建的模型,因為我無法訪問列表的屬性來填充視圖中的表:

    public class PurchaseHistoryModel
{
    public string Card { get; set; }

    public string User { get; set; }

    public string Group { get; set; }

    public decimal? Proceeds { get; set; }


}


public class PurchaseHistoryViewModel
{

    IPagedList<PurchaseHistoryModel> PurchaseList { get; set; }

}

}

我試圖將所有這些信息傳遞給一個可以做桌子頭的視圖,然后

@foreach(模型中的變量項)

然后使用@ model.Card,@ model.User,@ model進行訪問。 組,即我在將LINQ iQueryable強制轉換為哪種數據類型以將其傳遞到視圖中以仍然訪問所有屬性並從數據庫獲取行的整個列表時遇到問題。 有人可以幫我指出正確的方向嗎?

linq操作返回一個IQueryable ,它將解析為一個集合。 因此,您的模型將需要某種可枚舉的(我選擇在此處將其設為List ,但是您可以使用Collection或其他可枚舉的)。 您可以在linq查詢的末尾添加ToList()以避免延遲加載。

public ActionResult PurchaseHistory()
        {
            //Get White Label ID to filter results
            var whiteLabelId = new WhiteLabelHelper().GetWhiteLabelId();

            var model = new List<PurchaseHistoryModel>();



            model = (from pc in db.PurchasedCards
                                  join c in db.Cards on pc.CardId equals c.CardId
                                  join u in db.Users on pc.UserId equals u.UserId
                                  join g in db.FundraisingGroups on pc.GroupId equals g.GroupId
                                  where c.WhiteLabelId == whiteLabelId
                                  select new PurchaseHistoryModel { Card = c.Name, User = u.Name, Group = g.Name, Proceeds = pc.NPOProceeds }).ToList();



            return View(model);
        }

如果確實選擇使用@foreach (var item in model)訪問它@foreach (var item in model)則需要執行@item.Card, @item.User ... NOT @model.Card @item.Card, @item.User

暫無
暫無

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

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