集合的实体框架迁移

时间:2014-07-06 17:06:14

标签: asp.net-mvc entity-framework

我有一个看起来像这样的模型

public abstract class Item
{
    public int ItemId { get; set; }
    public String Title { get; set; }
    public String Description { get; set; }
    public DateTime PurchaseDate { get; set; }
    public ICollection<String> Pictures { get; set; }
    public Int32 MinimumPrice { get; set; }
    public DateTime Deadline { get; set; }
    public Boolean VisibleBids { get; set; }
    public Boolean Handled { get; set; }
    public DateTime PlacementDate { get; set; }
    public ApplicationUser User { get; set; }
}

在我的控制器中我做了

db.Items.ToList()

这使得所有获取对象的Pictures字段为null,因为它实体框架的工作方式。在一个查询中获取它们的好方法是什么?

1 个答案:

答案 0 :(得分:1)

我希望您已经完成了表之间的导航属性,现在您只需要将您的集合设置为虚拟,并在需要来自两个表的数据时使用预先加载的概念

public virtual ICollection<String> Pictures { get; set; }

并在linq中使用include

db.Items.Include("Pictures").ToList()

因此,通过虚拟导航,您只需要在需要时获取相关实体的数据,并在需要数据时使用Include进行预先加载。

有关设置导航属性的信息,请查看代码。

假设我们有Post的场景,我们有多个评论,如

 class Posts
{
   public int PostsId { get; set; }
   public string PostsDescription { get; set; }

   public virtual ICollection<Comments> Comments { get; set; } 
}

class Comments
{
   public int CommentsId { get; set; }
   public string CommentsDescription { get; set; }
   public int PostsId { get; set; }

   public virtual Posts Posts { get; set; }
}