简体   繁体   English

在asp.net核心api中返回集合

[英]return collection in asp.net core api

I have a small api with these models with ef-core 我有一个带有ef-core的这些模型的小型api

public class AppUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Company { get; set; }
    public ICollection<Account> Accounts { get; set; }
}

public class Account
{
    public int id { get; set; }
    public AppUser User { get; set; }
    public string AccountNumber { get; set; }
}

and I have a controller get function: 而且我有一个控制器的get函数:

[HttpGet]
public async Task<IActionResult> Home()
{
    // retrieve the user info
    //HttpContext.User
    var userId = _caller.Claims.Single(c => c.Type == "id");
    var user = await _appDbContext.Users.SingleAsync(c => c.Id == userId.Value);            

    return new OkObjectResult(new
    {
        Message = "This is secure API and user data!",
        user.FirstName,
        user.LastName,
        user.Accounts
    });
}

How do I get the controller to return the list of accounts? 如何让控制器返回帐户列表? In debug I can see the "accounts" variable with the correct data, I'm just not sure on how to format that var and return it in the api 在调试中,我可以看到带有正确数据的“ accounts”变量,但我不确定如何格式化该var并将其返回到api中

I am currently recievng: 我目前正在接收:

{
"message": "This is secure API and user data!",
"firstName": "Bill",
"lastName": "Johnson",
"serviceAccounts": null
}

UPDATE: So I ran the app using the dotnet command line and got 更新:所以我使用dotnet命令行运行了应用程序

{"firstName":"Bill","lastName":"Johnson","serviceAccounts":[{"id":1,"camsUser":{"firstName":"Bill","lastName":"Johnson","company":null

如果子实体设置为延迟加载,则您应该以以下方式获取帐户和用户

var user = await _appDbContext.Users.Include(u => u.Accounts).SingleAsync(c => c.Id == userId.Value); 

I figured it out with this: 我想出了这个:

var userId = _caller.Claims.Single(c => c.Type == "id");
var user = await _appDbContext.Users.Include(s =>s.Accounts).SingleAsync(c => c.Id == userId.Value);
var accounts = user.Accounts.Select(a => new
        {
            a.AccountNumber,
            a.id
        });
return new OkObjectResult(new
        {
            user.FirstName,
            user.LastName,
            accounts
        }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM