C# 在viewmodel中填充嵌套的ICollection

C# 在viewmodel中填充嵌套的ICollection,c#,asp.net,asp.net-mvc,linq,C#,Asp.net,Asp.net Mvc,Linq,我正试图找到一种填充嵌套集合模型的好方法。我的viewmodel中有以下内容 public class ListViewModel { public ICollection<Wish> Wishes { get; set; } } 我知道我可以做很多foreach语句,但我想利用LINQ用它们对应的图像填充每个愿望 **我确实有一个通用的repository类,它使我能够按照希望的方式检索所有图像 ***将存储库视为上下文。 因此,与其说它的愿望和想象,不如说它的智慧上下文

我正试图找到一种填充嵌套集合模型的好方法。我的viewmodel中有以下内容

public class ListViewModel
{
    public ICollection<Wish> Wishes { get; set; }
}
我知道我可以做很多foreach语句,但我想利用LINQ用它们对应的图像填充每个愿望

**我确实有一个通用的repository类,它使我能够按照希望的方式检索所有图像

***将存储库视为上下文。 因此,与其说它的愿望和想象,不如说它的智慧上下文和想象上下文


我正在使用ASP.NET Core 2.0实体框架Core

来加载相关实体,在查询
愿望
集合时,需要显式使用
Include
方法调用来加载
图像
属性

还要确保
等待
您的
异步
调用

var wishesWithImages = await yourDbContext.Wishes
                                          .Include(g => g.Images)
                                          .ToListAsync();
变量
wishesWithImages
将是加载了Images属性的
Wish
对象的集合。现在可以使用它来填充视图模型

var vm = new ListViewModel { Wishes = wishesWithImages  };
假设您的
Wish
实体具有类型为
Images

public class Wish
{
   public int Id { set;get;}
   public ICollection<Image> Images { set;get;} 
}
public class Image
{
   public int Id { set;get;}
   public int WishId { set;get;}
   public virtual Image Image{ set;get;} 
}
公共类愿望
{
公共int Id{set;get;}
公共ICollection映像{set;get;}
}
公众阶级形象
{
公共int Id{set;get;}
public int WishId{set;get;}
公共虚拟映像映像{set;get;}
}

到目前为止,Entity framework core是EF6的轻量级版本,不会自动继承EF6的所有功能。EF核心中尚未实现延迟加载

要加载相关实体,当您查询
愿望
集合以加载
图像
属性时,需要显式使用
包含
方法调用

还要确保
等待
您的
异步
调用

var wishesWithImages = await yourDbContext.Wishes
                                          .Include(g => g.Images)
                                          .ToListAsync();
变量
wishesWithImages
将是加载了Images属性的
Wish
对象的集合。现在可以使用它来填充视图模型

var vm = new ListViewModel { Wishes = wishesWithImages  };
假设您的
Wish
实体具有类型为
Images

public class Wish
{
   public int Id { set;get;}
   public ICollection<Image> Images { set;get;} 
}
public class Image
{
   public int Id { set;get;}
   public int WishId { set;get;}
   public virtual Image Image{ set;get;} 
}
公共类愿望
{
公共int Id{set;get;}
公共ICollection映像{set;get;}
}
公众阶级形象
{
公共int Id{set;get;}
public int WishId{set;get;}
公共虚拟映像映像{set;get;}
}

到目前为止,Entity framework core是EF6的轻量级版本,不会自动继承EF6的所有功能。EF核心中尚未实现延迟加载

\u repoWish.GetAllAsync()。
返回什么?在结果集中,
Image
实体和
Wish
实体是如何连接的?因此,您的愿望不会随数据库中的图像一起出现?如果需要,您需要循环或
linq
。您当前的代码有什么问题?@Shyju它返回一组愿望。但是这些愿望并没有被他们的愿望所满足images@adiga代码没有问题。我只需要一个额外的步骤来填充每个愿望的图像。
\u repoWish.GetAllAsync()。
返回什么?在结果集中,
Image
实体和
Wish
实体是如何连接的?因此,您的愿望不会随数据库中的图像一起出现?如果需要,您需要循环或
linq
。您当前的代码有什么问题?@Shyju它返回一组愿望。但是这些愿望并没有被他们的愿望所满足images@adiga代码没有问题。我只需要一个额外的步骤来填充每个愿望与他们的图像。那么,当查询“wishesWithImages”的愿望与图像填充?是的,图像有一个愿望是的。wishesWithImages是已填充Images属性的愿望集合。因此,当查询“wishesWithImages”时,愿望是否已填充图像?是的,图像有一个愿望是的。wishesWithImages是已填充Images属性的愿望集合。