c# - 如何从数据库中获取特定字段?
问题描述
public class UserController : ApiController
{
UserSampleEntities entities = new UserSampleEntities();
// GET api/<controller>
[Route("api/User")]
public IEnumerable<user> Get()
{
{
return entities.users;
}
}
}
这将返回包含数据库中所有条目及其所有属性的 json。如何进行过滤,以便仅获取特定属性的 json?
解决方案
创建一个新类,该类仅使用您要公开的属性来代表用户"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();
}
推荐阅读
- android-studio - 包名/SHA1
- node.js - nodejs - 证书已过期
- mongodb - 如何在 Mongo 中合并列
- flutter - 未处理的异常:NoSuchMethodError:在 null 上调用了 getter 'focusScopeNode'
- c - 我有一个警告“传递 'bins' 的参数 2 从没有强制转换的指针中生成整数”
- jquery - jquery 脚本仅适用于第一个输入。不适用于动态生成的相同
- nginx - 无法重定向IP,我得到了错误。那么我该如何解决呢?
- java - 在java中的循环之外编写sout语句
- php - 如何安全地存储我的 cronjobs 的脚本?
- python - 删除链表中的节点的问题(Python)