首页 > 解决方案 > 如何从数据库中获取特定字段?

问题描述

public class UserController : ApiController
    {
        UserSampleEntities entities = new UserSampleEntities();
      
        // GET api/<controller>
        [Route("api/User")]
        public IEnumerable<user> Get()
        {

            {
                return entities.users;

            }
        }
   }

这将返回包含数据库中所有条目及其所有属性的 json。如何进行过滤,以便仅获取特定属性的 json?

标签: c#asp.netlistlinqienumerable

解决方案


创建一个新类,该类仅使用您要公开的属性来代表用户"api/User"

public class UserDto
{
    public int Foo { get; set; }

    public string Bar { get; set; }

    // add the properties you need here
}

将您的 API 操作重写为:

[Route("api/User")]
public IEnumerable<UserDto> Get()
{
    return entities.users
        .Select(u => new UserDto
        {
            Foo = u.Foo,
            Bar = u.Bar,
            // map the properties you need here
        })
        .ToArray();
}

推荐阅读