当子对象不是列表或集合时,包括子对象和子对象

时间:2017-03-18 11:44:52

标签: c# .net entity-framework linq

您好我正试图通过linq

包含儿童和儿童的对象

这是我的父类

public class SharePost : BasePost
{
    public Address Address { get; set; }

    public ICollection<Picture> Pictures { get; set; }
}

这是我的孩子班,这是&#34;地址&#34;

public class Address
{
    public SharePost SharePost { get; set; }
    public int PostId { get; set; }

    public Place Place { get; set; }
    public int PlaceId { get; set; }

    public Suburb Suburb { get; set; }
    public int SuburbId { get; set; }
}

基本上,SharePostAddress是一对一的关系。所以它们具有相同的主键值。然后我想在加载SharePost对象时包含PlaceSuburb对象。所以我尝试了这个

public SharePost GetFullSharePost(int postId)
{
   return DataContext.SharePosts.Include(m => m.Address.Select((a => a.Suburb)) && (a => a.Place))
}

Address.Select()不起作用。 Asp.net无法识别地址上的Select()方法。 Select()仅适用于列表或ICollection吗?那么当我加载Place对象时,如何在Suburb中包含AddressSharepost对象?

1 个答案:

答案 0 :(得分:2)

如果要包含集合,则应使用Select。试试这个:

return DataContext.SharePosts
    .Include(x => x.Address.Suburb)
    .Include(x => x.Address.Place);