使用LINQ多对多(MTM)关联查询时遇到的困难

时间:2012-10-26 13:46:32

标签: entity-framework linq-to-entities

恕我直言,我认为这对我来说是最困难的事情 - LINQ的整个MTM方面我需要帮助。

在SQL中,我有3个表:AccountsAccountsInFeaturesFeaturesAccountsInFeatures只有两个主键列,可链接到AccountsFeatures

在EF中,AccountsInFeatures不可见 - 我理解为什么 - 但是我在创建LINQ时遇到了问题:

这是我正在尝试做的事情:

return (from a in _Store.Accounts
        where a.AccountGUID == _AccountGUID
        select new AccountDetails
        {
            AccountGUID = a.AccountGUID
            AccountName = a.AccountName,
            SelectedFeatures = a.Features.Select(f => f.FeatureGUID).ToList()
        }).ToList();

以下是AccountDetails的定义:

public class AccountDetails
{
    public Guid AccountGUID { get; set; }
    public string AccountName { get; set; }  
    public List<Guid> SelectedFeatures { get; set; }    
}

如何填写"SelectedFeatures"功能列表 - 这可能吗?我接近将它分成两个查询=)

1 个答案:

答案 0 :(得分:1)

这样做:

public class AccountDetails
{
    public Guid AccountGUID { get; set; }
    public string AccountName { get; set; }  
    public Collection<Features> SelectedFeatures { get; set; }    
}

return (from a in _Store.Accounts
        where a.AccountGUID == _AccountGUID
        select new AccountDetails
        {
            AccountGUID = a.AccountGUID
            AccountName = a.AccountName,
            SelectedFeatures = a.Features
        }).ToList();