簡體   English   中英

實體框架+模型+ 2個表格+列表

[英]Entity Framework + Model + 2 Tables + List

我對LINQ結果有疑問

  • 我的數據庫結構

在此處輸入圖片說明

[外鍵]-> [主鍵(主鍵表)]

[companyFK]-> [companyID(companyTable)]

[billFK]-> [billerID(billerTable)]

[attFK]-> [attentedID(attentedTable)]

在此處輸入圖片說明

*這是我的發票模型(此模型隨ADO.NET實體框架自動提供)

namespace pcis
{
using System;
using System.Collections.Generic;

public partial class invoiceTable
{
    public int invoiceID { get; set; }
    public Nullable<int> companyFK { get; set; }
    public string currency { get; set; }
    public Nullable<decimal> amt { get; set; }
    public Nullable<System.DateTime> startDate { get; set; }
    public Nullable<System.DateTime> endDate { get; set; }
    public Nullable<int> billFK { get; set; }
    public Nullable<int> attFK { get; set; }
    public string status { get; set; }

    public virtual attentedTable attentedTable { get; set; }
    public virtual billerTable billerTable { get; set; }
    public virtual companyTable companyTable { get; set; }
}
}
  • 這是我的發票表的數據訪問層代碼,在此類中,我將獲取每個數據並將其存儲到列表中並返回列表

     using (var db = new PcisDBContext()) { retAllInvoicesList = db.invoiceTables.ToList(); } return retAllInvoicesList; 

****問題:****如您在代碼和圖片中所看到的,我僅返回外鍵編號。 代替外鍵,我應該顯示其行的另一個字段,例如[company ID to company Name]。

可能的解決方案:我可以到達列表的每一行,並從外鍵的原始表中獲取所有數據,並從特定表中替換它們。 但是,在我的模型中,有3個虛擬變量,我以為可以使用它們解決此問題,但找不到

    public virtual attentedTable attentedTable { get; set; }
    public virtual billerTable billerTable { get; set; }
    public virtual companyTable companyTable { get; set; }

在此處輸入圖片說明

您可以創建如下的視圖模型:

public class InvoiceViewModel
{
    public int invoiceID { get; set; }
    public string companyName { get; set; }
    public string currency { get; set; }
    public decimal? amt { get; set; }
    public DateTime? startDate { get; set; }
    public DateTime? endDate { get; set; }
    public string billerName { get; set; }
    public string attentedName { get; set; }
    public string status { get; set; }
}

然后將值分配給ViewModel的每個屬性:

    using (var db = new PcisDBContext())
    {
        var retAllInvoicesList= db.invoiceTables.Select(m => new InvoiceViewModel
        {
            invoiceID = m.invoiceID,
            companyName = m.companyTable.companyName,
            currency = m.currency,
            amt = m.amt,
            startDate = m.startDate,
            endDate = m.endDate,
            billerName = m.billerTable.billerName,
            attentedName = m.attentedTable.attentedName,
            status = m.status
        });
    }
   return retAllInvoicesList;

最后,您可以使用InvoiceViewModel ViewModel創建一個強類型的視圖。

注意:默認情況下,延遲加載是啟用的,如果您禁用了延遲加載,則上述查詢將不起作用。

暫無
暫無

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

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