簡體   English   中英

在實體框架中查詢,包含 Select 語句

[英]Querying in Entity Framework, Select Statement within include

我正在嘗試塑造 HTTP GET 請求,其中顯示實體牆及其一些父表(用戶)行。 我成功地獲得了整個父行,但是我在 select 語句中掙扎,我想在響應中選擇我想要的行和值。

[HttpGet]
        public async Task<ActionResult<IEnumerable<Wall>>> GetWalls()
        {

            return await _context.Walls
                .Include(p=>p.User)
                .ToListAsync();
        }

我的回復如下所示:

{
        "wallID": "46d7389f-2dcd-4b52-b4c0-32e7bbf5af24",
        "wallName": "erfnoerng",
        "dateCreated": "2020-07-31T11:53:21.9217551",
        "dateUpdated": null,
        "userID": "274eed93-fedf-4825-9c11-deb1e7678b99",
        "user": {
            "fullName": "Phil Hearing",
            "wall": [],
            "id": "274eed93-fedf-4825-9c11-deb1e7678b99",
            "userName": "philcuAdmin",
            "normalizedUserName": "PHILCUADMIN",
            "email": "phil@gmail.com",
            "normalizedEmail": "PHIL@GMAIL.COM",
            "emailConfirmed": false,
            "passwordHash": "AQAAAAEAACcQAAAAECPcBzMuCBrvo5jfSvRC8htiBMcXY6uHPymLvLLpqTOQc0iiYO9mB7XS82O0f2OEkA==",
            "securityStamp": "DCYN6LTUSAP3HSAD6ZEENPJ6CPZXCDAO",
            "concurrencyStamp": "fb06525c-0bad-4f06-bbdd-8f4404097a54",
            "phoneNumber": null,
            "phoneNumberConfirmed": false,
            "twoFactorEnabled": false,
            "lockoutEnd": null,
            "lockoutEnabled": true,
            "accessFailedCount": 0
        },
        "groupATerms": null,
        "groupBTerms": null,
        "groupCTerms": null,
        "groupDTerms": null,
        "groupAConnections": null,
        "groupBConnections": null,
        "groupCConnections": null,
        "groupDConnections": null
    }

我只想從父表中獲取用戶名、email 和 fullName,但是當我編寫時出現錯誤。Select 語句表示 Select 在當前上下文中不存在。

像這樣創建一個 ViewModel:

public class DataViewModel
{
  public string FullName{ get; set; }
  public string Email{ get; set; }
  public string UserName{ get; set; }
}

接着:

[HttpGet]
public async Task<ActionResult> GetWalls()
{
    var result = await _context.Walls.Include(p=>p.User).Select(usr => new DataViewModel()
    {
        UserName = usr.User.UserName,
        Email= usr.User.Email,
        FullName= usr.User.FullName
    }).ToListAsync();

   return Ok(result);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM