控制器:
public ActionResult Index()
{
var Cs = new List<Customer>();
using (JoinEntities db = new JoinEntities())
{
Cs = (from p in db.Customers
join e in db.Orders on p.ID equals e.Customer_id
where p.Name == "Rama"
select p).ToList();
}
return View(Cs);
}
查看:
@model IEnumerable<JOIN.Models.Customer>
@{
ViewBag.Title = "Home Page";
}
<table class="table table-condensed table-hover">
<thead>
<tr>
<td>First Name</td>
<td>salary</td>
<td>age</td>
<td>amount</td>
</tr>
</thead>
<tbody>
@foreach (var per in Model)
{
<tr>
<td>@per.ID</td>
<td>@per.Name</td>
<td>@per.Age</td>
<td>@per.Amount</td>
</tr>
}
</tbody>
</table>
上面的代码视图是仅占用一个表列,如何才能获得客户表中的其他表列?id是主键,而订单表customer_id
是外键
customer
表:id,姓名,年龄,薪水列order
表:oid,日期,customer_id,金额列答案 0 :(得分:0)
您需要创建另一个模型
class MyModel{
public string Name{get;set;}
public DateTime Date {get;set;}
}
并更改选择查询:
var Cs = new List<MyModel>();
using (JoinEntities db = new JoinEntities())
{
Cs = (from p in db.Customers
join e in db.Orders on p.ID equals e.Customer_id
where p.Name == "Rama"
select new MyModel {
Name = p.Name,
Date = e.date
}).ToList();
}
答案 1 :(得分:0)
如下创建另一个视图模型
Rails.cache.fetch(key, &block)
# ↑
并如下更新您的Index方法
public class CustomerOrderViewModel
{
public int CustomerId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public double Salary { get; set; }
public int OrderId { get; set; }
public DateTime Date { get; set; }
public double Amount { get; set; }
}
并将视图的视图模型更改为
public ActionResult Index()
{
using (JoinEntities db = new JoinEntities())
{
var customerOrderList = (from p in db.Customers
join e in db.Orders on p.ID equals e.Customer_id
where p.Name == "Rama"
select new CustomerOrderViewModel {
CustomerId = p.Id,
Name = p.Name,
Age= p.Age,
Salary = p.Salary,
OrderId= e.Id,
Date= e.Date,
Amount = e.Amount
}).ToList();
return View(customerOrderList);
}
}