【发布时间】:2021-05-15 00:59:32
【问题描述】:
目前,在我的控制器的服务方法GetSubAccounts(accountId)中,我有这个:
Account account = await context.Accounts.SingleOrDefaultAsync(x => x.Id == accountId);
IQueryable<Account> subAccounts = context.Accounts.Include(x => x.AccountCodes).AsNoTracking();
return await mapper.ProjectTo<SubAccountViewModel>(subAccounts, null, x => x.SubAccounts)
.Where(x => x.PersonId == account.PersonId && x.AccountId != null).ToListAsync();
我的SubAccountViewModel如下:(注意它自己有一个集合)
public class SubAccountViewModel : Base.AccountViewModel
{
public virtual ICollection<AccountCodeViewModel> AccountCodes { get; set; }
public virtual ICollection<SubAccountViewModel> SubAccounts { get; set; }
}
我的映射配置文件是:
internal class SubAccountMappingProfile : Profile
{
public SubAccountMappingProfile()
{
CreateMap<Account, SubAccountViewModel>()
.ForMember(x => x.AccountCodes, options => options.ExplicitExpansion())
.ForMember(x => x.SubAccounts, options => options.ExplicitExpansion())
.ReverseMap();
}
}
这是我得到的 JSON:
[
{
"id":"c236718f-9d91-4eea-91ee-66760a716343",
"personId":"06d3857d-6a49-4e1c-b63c-7edc83d30cbd",
"accountId":null,
"username":"test same person",
"email":"testsameperson@gmail.com",
"birthDate":"2021-01-02",
"subaccounts":null
}
]
问题:
我正在为传递给方法的accountId 参数获取顶级子帐户数组。美好的。 (只有一个,但没关系。)
我做想要的是顶级的主帐户,以及子帐户数组作为其中的一部分。
即
{
"id":"f61fedc2-eb60-4ba9-9d17-8d41b9cae9f1",
"personId":"06d3857d-6a49-4e1c-b63c-7edc83d30cbd",
"accountId":"f61fedc2-eb60-4ba9-9d17-8d41b9cae9f1",
"username":"test person",
"email":"testperson@gmail.com",
"birthDate":"2021-01-01",
"subaccounts":[
{
"id":"c236718f-9d91-4eea-91ee-66760a716343",
"personId":"06d3857d-6a49-4e1c-b63c-7edc83d30cbd",
"accountId":"f61fedc2-eb60-4ba9-9d17-8d41b9cae9f1",
"username":"test same person",
"email":"testsameperson@gmail.com",
"birthDate":"2021-01-02",
"subaccounts":null
}
]
}
我该怎么做?
【问题讨论】:
-
在第一个代码块中,第二行变量似乎不正确??作为
AccountCodes而不是SubAccounts? -
@AjeetKumar 不,因为
AccountCodes也是SubAccountViewModel的集合(参见第二个代码块中的SubAccountViewModel定义)。子帐户与主帐户的类型相同,这使事情变得复杂。我需要在查询中.Include()AccountCodes,否则它将映射到null。 -
你试过不使用自动映射器吗?
-
@AjeetKumar No.
-
请试一试
标签: c# arrays asp.net-core asp.net-web-api automapper