Linq查询预期结果

时间:2014-03-07 06:01:10

标签: c# asp.net-mvc linq

public class Actor
    {
        public virtual int Id { get; set; }    
        public virtual string Name { get; set; }
        public virtual string ShortName { get; set; }  
        public virtual IList<BankAccount> BankAccounts { get; set; }
    }
public class BankAccount 
    {
        public virtual int Id { get; set; }
        public virtual string IbanPrefix { get; set; }
        public virtual string Number { get; set; }
    }
public class BankAccountModel
{
    public int Id { get; set; }
    public string IbanPrefix { get; set; }
    public string Number { get; set; }
}
public BankAccountModel[] BankAccounts { get; set; }

我想使用linq查询选择特定actor Id的数组Bank Accounts属性中的所有银行账户。

我试过如下

var query = Repository.Query<Actor>().Where(a => a.Id == parameters.ActorId)
                        .Select(a => a.BankAccounts);

            BankAccounts  = query.Select(account => account.Select(a=>
                                   new BankAccountModel
                                   {
                                      Description = a.Description,
                                       IbanPrefix = a.IbanPrefix,
                                       Id = a.Id,
                                       Number = a.Number
                                   }).ToArray());

但它不适合我。

1 个答案:

答案 0 :(得分:1)

Repository
 .Query<Actor>()
 .Where(a => a.Id == actorId)
 .SelectMany(a => a.BankAccounts)
 .Select(ba => new BankAccountModel
                   {
                       IbanPrefix = ba.IbanPrefix,
                       Id = ba.Id,
                       Number = ba.Number
                   }
        );

如果您想将actros bankaccounts与BankAccounts属性相匹配,请尝试以下此类内容,

Repository
 .Query<Actor>()
 .Where(a => a.Id == actorId)
 .SelectMany(a => a.BankAccounts)
 .Where(ba => BankAccounts.Any(ac => ac.Id == ba.Id))
 .Select(ba => new BankAccountModel
                   {
                       IbanPrefix = ba.IbanPrefix,
                       Id = ba.Id,
                       Number = ba.Number
                   }
        );