在ASP.NET MVC中,可以使用LINQ和Entity Framework来查询数据库并将结果映射到视图模型中。
以下是一个示例代码,演示如何使用LINQ查询SQL数据库并将结果映射到视图模型中:
public class CustomerViewModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }
}
public ActionResult Index()
{
using (var db = new YourDbContext())
{
var customers = db.Customers.Select(c => new CustomerViewModel
{
Name = c.Name,
Email = c.Email,
Address = c.Address
}).ToList();
return View(customers);
}
}
在上面的代码中,我们使用LINQ的Select方法来选择所需的属性,并将它们映射到CustomerViewModel对象中。使用ToList方法将结果转换为列表,并将其传递给视图。
@model List
@foreach (var customer in Model)
{
@customer.Name
Email: @customer.Email
Address: @customer.Address
}
在上面的代码中,我们使用@model指令指定视图模型类型为CustomerViewModel列表。然后,我们使用foreach循环遍历列表,并通过@customer变量访问每个客户的属性。
以上就是使用LINQ和Entity Framework查询数据库并将结果映射到ASP.NET MVC视图模型的示例代码。请根据实际情况进行调整和修改。