簡體   English   中英

如何執行兩個集合的聯接並填充導航屬性

[英]How to perform a join of two sets and populate navigation properties

假設我有兩個課, TeapotCup

public class Teapot
{
    [Key]
    [Column("Id", TypeName = "int")]
    public int Id         { get; set; }

    public int MaterialId { get; set; }

    public int ColorId    { get; set; }

    [ForeignKey("MaterialId")]
    public virtual Material Material { get; set; }
    [ForeignKey("ColorId")]
    public virtual Color    Color    { get; set; }
}

public class Cup
{
    [Key]
    [Column("Id", TypeName = "int")]
    public int Id         { get; set; }

    public int MaterialId { get; set; }

    public int ColorId    { get; set; }

    [ForeignKey("MaterialId")]
    public virtual Material Material { get; set; }
    [ForeignKey("ColorId")]
    public virtual Color    Color    { get; set; }
}

這是我的ViewModel:

namespace ViewModel.Data
{
    public class TeapotsWithInfo
    {
        public Model.Data.Teapot Teapot { get; set; }
        public Model.Data.Cup    Cup    { get; set; }
    }
}

對於我的ViewModel ,我需要對MaterialId和ColorId執行聯接,並包含一些導航屬性,例如Teapot.Material.Manufacturer 因此,我嘗試了以下查詢:

  1. 這將引發“ LINQ to Entities僅支持轉換EDM基本類型或枚舉類型”

     (from t in db.Teapots join c in db.Cups on new { t.MaterialId, t.ColorId } equals new { c.MaterialId, c.ColorId } where t.Id == id select new ViewModel.Data.TeapotsWithInfo { Teapot = t, Cup = c }) .Include(t => t.Material.Manufacturer).SingleOrDefault(); 
  2. 這似乎忽略了Include

      (from t in db.Teapots.Include(t => t.Material.Manufacturer) join c in db.Cups on new { t.MaterialId, t.ColorId } equals new { c.MaterialId, c.ColorId } where t.Id == id select new ViewModel.Data.TeapotsWithInfo { Teapot = t, Cup = c }).SingleOrDefault(); 

現在,我在這里找到了一些答案,建議先進行枚舉,然后再執行另一個選擇,但我寧願一口氣捕獲數據。

您遇到的困難包括導航性能,因為與連接的查詢或預測忽略預先加載(見 )。

不幸的是,您將需要做的事情似乎是避免的:首先從數據庫中提取數據,然后再進行其他選擇以構建ViewModel(它將從原始查詢中加載關系)。 但是,由於沒有從數據庫中執行額外的加載,因此,附加選擇應該是相當瑣碎的操作,可枚舉應僅包含一個項目。

(from t in db.Teapots.Include(t => t.Material.Manufacturer)
 join c in db.Cups
 on new { t.MaterialId, t.ColorId } equals new { c.MaterialId, c.ColorId }
 where t.Id == id
 select new 
  {
     Teapot = t,
     Cup = c,
     Material = t.Material,
     Manufacturer = t.Material.Manufacturer,
  })
.AsEnumerable()
.Select(a => new ViewModel.Data.TeapotsWithInfo 
  { 
     Teapot = a.Teapot, 
     Cup = a.Cup 
  })
.SingleOrDefault();

資源

暫無
暫無

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

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