1

ASP NET Core 6/EF Core 6. Есть эндпоинт, который выдает некоторые данные:

[HttpGet]
[Authorize]
public async Task<ActionResult<Contact[]>> Get()
{
    return Ok(await _context.Contacts.Where((x) => x.Owner == _userService.GetUser())
        .Include((x) => x.Owner).Include((x) => x.Target).ToListAsync());
}

введите сюда описание изображения

Но я хотел бы избавиться от всех значений в блоках owner и target, кроме firstName, lastName и grade.

Теги [JsonIgnore] не подходят, так как они уже используются для сокрытия значений для другого эндпоинта.

Попробовал реализовать это с помощью ThenInclude, включив только нужные мне поля:

[HttpGet]
[Authorize]
public async Task<ActionResult<Contact[]>> Get()
{
    return Ok(await _context.Contacts.Where((x) => x.Owner == _userService.GetUser())
        .Include((x) => x.Owner).ThenInclude((owner) => owner.FirstName)
        .Include((x) => x.Owner).ThenInclude((owner) => owner.LastName)
        .Include((x) => x.Owner).ThenInclude((owner) => owner.Grade)
        .Include((x) => x.Target).ThenInclude((target) => target.FirstName)
        .Include((x) => x.Target).ThenInclude((target) => target.LastName)
        .Include((x) => x.Target).ThenInclude((target) => target.Grade).ToListAsync());
}

Но такая реализация всегда выдаёт исключение:

System.InvalidOperationException: The expression 'owner.FirstName' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty'). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.

Модель Contact:

public class Contact : Auditable
{
    public int Id { get; set; }

    public User Owner { get; set; } = new User();
    public User Target { get; set; } = new User();
}

Модель User:

public class User : Auditable
{
    [JsonIgnore]
    public int Id { get; set; }

    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;

    public string Email { get; set; } = string.Empty;

    public School School { get; set; } = new School();
    public string Grade { get; set; } = string.Empty;

    [JsonIgnore]
    public byte[] PasswordHash { get; set; } = new byte[] { };
    [JsonIgnore]
    public byte[] PasswordSalt { get; set; } = new byte[] { };

    [JsonIgnore]
    public bool Verified { get; set; }
    [JsonIgnore]
    public string Role { get; set; } = string.Empty;
}
6
  • 1
    В тексте ошибки же написано все подробно.
    – aepot
    4 окт 2022 в 17:40
  • .Include((x) => x.Owner.FirstName) не катит?
    – aepot
    4 окт 2022 в 18:22
  • @aepot не катит: ...System.InvalidOperationException: The expression 'x.Owner.FirstName' is invalid inside an 'Include' operation... 4 окт 2022 в 18:25
  • Давайте вопрос по-другому поставим, покажите запрос, который работает, покажите что он возвращает клиенту, и скажите, что там не так, и какого результата вы желаете добиться. Отредактируйте вопрос.
    – aepot
    4 окт 2022 в 18:33
  • зачем ThenInclude((owner) => owner.FirstName) вообще надо? Просто .Include((x) => x.Owner) не работает? Оно же все проперти само должно подтянуть
    – tym32167
    4 окт 2022 в 18:38

1 ответ 1

2

Include(x => x.Owner) загрузит все свойства User, являющиеся примитивными типами (вернее, загрузит все данные, хранящиеся в этой же таблице БД). Чтобы избежать этого, можно сделать проекцию с помощью Select, явно указав нужные свойства.

Должно работать примерно следующее:

await _context.Contacts.Where(x => x.Owner == user)
    .Include(x => x.Owner)
    .Include(x => x.Target)
    .Select(x => new //Contact
    {
        //Id = x.Id,
        Owner = new //User
        {
            //Id = x.Owner.Id,
            FirstName = x.Owner.FirstName,
            LastName = x.Owner.LastName,
            Grade = x.Owner.Grade,
        },
        Target = new //User
        {
            //Id = x.Target.Id,
            FirstName = x.Target.FirstName,
            LastName = x.Target.LastName,
            Grade = x.Target.Grade
        }
    })
    .ToListAsync();

Вместо анонимных типов можете сделать Contact и User, если необходимо.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.