如何从数据库中获取特定字段?
How to get specific field(s) from database?
public class UserController : ApiController
{
UserSampleEntities entities = new UserSampleEntities();
// GET api/<controller>
[Route("api/User")]
public IEnumerable<user> Get()
{
{
return entities.users;
}
}
}
此 returns json 包含数据库中的所有条目及其所有属性。如何进行过滤以便仅针对特定属性获得 json?
创建一个新的 class 代表一个用户,只使用您想要从 "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();
}
public class UserController : ApiController
{
UserSampleEntities entities = new UserSampleEntities();
// GET api/<controller>
[Route("api/User")]
public IEnumerable<user> Get()
{
{
return entities.users;
}
}
}
此 returns json 包含数据库中的所有条目及其所有属性。如何进行过滤以便仅针对特定属性获得 json?
创建一个新的 class 代表一个用户,只使用您想要从 "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();
}