仅包含一个属性,而不是整个数据库行

Pio*_*rek 5 c# asp.net entity-framework entity-framework-core asp.net-core

模型:

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; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

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

我的控制器现在返回整个ApplicationUser类,它是属性之一Word.我只想发送一个属性ApplicationUser:UserName.我怎样才能做到这一点?

我添加了AuthorName,它只返回我想要的数据ApplicationUser.不幸的是,我仍然需要.Include(x=>x.Author)使这个属性工作.我可以Author在某种程度上省略包括在数据序列化过程中(在向用户发送数据时隐藏它)吗?

我知道我可以使用.Select()方法,但它需要我输入我需要的所有属性.如果我将来修改我的模型,我将需要更新所有那些.Select()不方便和浪费时间的方法.

你会如何解决这个问题?

Tse*_*eng 5

您需要创建一个 Dto 对象并向其分配值并返回 Dto。

达托

public class WordDto 
{
    public string Title { get; set; }
    public DateTime? WhenCreated { get; set; }
    public string AuthorName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

那么在你的行动中

[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();
}
Run Code Online (Sandbox Code Playgroud)