使用控制器,我可以获取所有数据库的用户表,但如果我想只获得用户"电子邮件"列,我应该怎么写这个控制器?
public ActionResult Index()
{
var users = db.Users.Where(d => d.Subscriptions.Any(x => x.Status == true));
return View(users.ToList());
}
答案 0 :(得分:1)
您只能.Select
所需的列:
public ActionResult Index()
{
var users = db.Users
.Where(d => d.Subscriptions.Any(x => x.Status == true))
.Select(u => u.Email);
return View(users);
}
请注意,在这种情况下,您将返回IEnumerable<string>
(我认为Email
属性为字符串)
如果要返回更复杂的内容,则应创建一个只包含所需属性的新对象,例如:
public class UserWithEmail
{
public int UserId { get; set; }
public string Email { get; set; }
}
然后:
public ActionResult Index()
{
var users = db.Users
.Where(d => d.Subscriptions.Any(x => x.Status == true))
.Select(u => new UserWithEmail() { UserId = u.UserId, Email = u.Email };
return View(users);
}