繁体   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