Include only one property, not an entire database row.

Model:

public class Word
{
    public int ID { get; set; }
    public string Title { get; set; }
    public DateTime? WhenCreated { get; set; }
    public ApplicationUser Author { get; set; }

    [NotMapped]
    public string AuthorName
    {
        get
        {
            if (Author != null)
            {
                return Author.UserName;
            }
            else {
                return "";
            }
        }
    }

    public List<Definition> Definitions { get; set; }
}

Controller:

[HttpGet]
    public IEnumerable<Word> Get()
    {
        return _db.Words.Include(x=>x.Author).ToList();
    }

Now My Controller returns the entire class ApplicationUser, which is one of the properties Word. I want to send only one property ApplicationUser: UserName. How can i do this?

I added AuthorNamethat will only return the data that I want from ApplicationUser. Unfortunately, I still need .Include(x=>x.Author)this property to work. Can I somehow omit, including Authorduring data serialization (to hide it when sending data to the user)?

, .Select(), . , .Select(), .

?

+4
4

Dto , Dto.

Dto

public class WordDto 
{
    public string Title { get; set; }
    public DateTime? WhenCreated { get; set; }
    public string AuthorName { get; set; }
}

[HttpGet]
public async Task<IEnumerable<WordDto>> Get()
{
    return _db.Words
              .Include(x=>x.Author)
              .Select(x =>
                  new WordDto 
                  {
                      Title = x.Title,
                      DateTime = x.WhenCreated,
                      AuthorName = x.Author?.UserName ?? string.Empty
                  }
              )
              .ToListAsync();
}
+4

, .

. Include.

    [HttpGet]
    public async Task<IEnumerable<Word>> Get()
    {
        return _db.Words.Select(x => new  
                      {
                          Word = x,
                          AuthorName = x.Author.UserName
                      }
                  ).ToList();
    }
+2

View AutoMapper . AutoMapper ProjectTo https://github.com/AutoMapper/AutoMapper/wiki/Queryable-Extensions

, View Model, , EF.

, , (. AutoMapper ):

public class WordVM 
{
    public string Title { get; set; }
    public DateTime? WhenCreated { get; set; }
    public string AuthorName { get; set; }
}

AutoMapper ( , , , VM, )

  _db.Words.ProjectTo<WordVM>().ToList();

NotMapped. AutoMapper Author Author Name AuthorName

+1

My workaround was to get all the related objects with .include (), then iterate over them and omit property values ​​that I did not want to return. This will require some maintenance if your model is changed, but it is surprising that it did not affect the response time.

0
source

Source: https://habr.com/ru/post/1658534/


All Articles