【问题标题】:Is there any way to load ApplicationUser some columns only?有没有办法只加载 ApplicationUser 一些列?
【发布时间】:2021-04-23 08:20:16
【问题描述】:

我有一个与 ApplicationUser Model.From 控制器相关的 Post 模型类,当我急切加载 ApplicationUsers 时,这里加载了所有数据。我不想加载用户密码。我只想加载用户一些列数据。

模型类:

public class Post
{
    public int PostId { get; set; }        
    public string PostContent { get; set; }
    public string ClientId { get; set; }
    public ApplicationUser Client { get; set; }      
}

控制器:

var Post = await _context.Post.Include(x=>x.Client).ToListAsync();

注意:我使用的是 .Net Core Indentity。

感谢阅读。

【问题讨论】:

    标签: c# entity-framework asp.net-core


    【解决方案1】:

    我不相信您只能选择.Client 的某些属性。但是,您可以使用 dto:

     var PostDto = await _context.Post
        //.Where
        .Select( p => new PostDTo {
            PostId,
            PostContent, 
            Username = p.Client.UserName
     })
     .ToListAsync();
    

     var PostDto = await _context.Post
        //.Where
        .Select( p => new PostDTO {
            PostId,
            PostContent, 
            User = new UserDTO 
            { 
               p.Client.UserName,
               ...
            }
     })
     .ToListAsync();
    

    请注意,通过使用 DTO 而不是公开表,您可以保证永远不会公开不需要的数据。

    【讨论】:

    • 我并不关心 DTO。现在我完成了我的任务。感谢帮助。 #保持安全。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2015-01-15
    • 2021-02-15
    • 2012-10-25
    相关资源
    最近更新 更多