如何执行两个集合的连接并填充导航属性



假设我有两个类,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();

  • http://thedatafarm.com/data-access/use-projections-and-a-repository-to-fake-a-filtered-eager-load/

相关内容

  • 没有找到相关文章

最新更新