在做项目的时候EF的单表不一定能够满足我们的项目需求。有时候需要查找的数据会涉及几张表示很正常的。这个时候就需要我们另外写一个模型类,自定义查询的数据了。
首先,将需要的字段新建一个类,在项目---Models中新建一个类文件。我建立的文件名为:ToolsDels。
代码:
public class ToolsDels
{
public int id { get; set; } //tools表
public string MatId { get; set; }//tools表
public string MatName { get; set; }//tools表
public string MatDesc { get; set; }//tools表
public string Unit { get; set; }//tools表
public string Memo { get; set; }//tools表
public string Price { get; set; }//tools表
public string local { get; set; }***//toolocal表***
public string scort { get; set; }***//toolscort表***
public Nullable<int> depotqty { get; set; }
}
然后再Control中写上逻辑:
SQLDBEntities sqldb = new SQLDBEntities(); //实例化EF实体类
// GET: ToolsManager
public ActionResult Index()
{
List<ToolsDels> list = new List<Models.ToolsDels>(); //使用泛型接收数据
list = (from a in sqldb.tools
join b in sqldb.toollocal on a.localid equals b.id
join c in sqldb.toolsort on a.tooltype_id equals c.id //Linq语法。跟SQL语句差不多,只是宾谓相反而已,反正我是这么理解的。
select new ToolsDels() //将在LINQ中查询的数据放到模型中。
{
id = a.id,
MatId = a.MatId,
MatDesc = a.MatDesc,
MatName = a.MatName,
Unit = a.Unit,
Memo = a.Memo,
Price = a.Price,
local = b.title,
scort = c.title,
depotqty=a.depotqty
}
).ToList();
return View(list); //返回数据
}
Index文件中的代码如下:
@model IEnumerable<InsidManager.Models.ToolsDels> //重要,需要在这里先声明Item所使用的Models,要不然会找不到数据模型。
@{
ViewBag.Title = "刀具管理";
}
@Styles.Render("~/Content/Toolsmanager.css"); //声明需要使用的css路径
<h3>
刀具管理
</h3>
<p>
@Html.ActionLink("新增", "Create")
</p>
@{
var grid = new WebGrid(Model,canPage:true,rowsPerPage:5); //每页显示5条记录,这个数字会影响到分页里每页数据的行数,我这里使用的是5
@grid.GetHtml(
tableStyle: "Toolsa", //使用的CSS文件
headerStyle: "ToolsB",
columns: grid.Columns(
grid.Column("matid", "编号", style: "matid", format:@<b>@item.matid</b>),
grid.Column("Matname", "品名", style: "MatName"),
grid.Column("MatDesc", "规格", style: "MatDesc"),
grid.Column("Unit","单位",style:" Unit"),
grid.Column("Price","单价",style:"Price"),
grid.Column("local", "仓位",style: "local"),
grid.Column("scort", "分类",style: "scort"),
grid.Column("depotqty"," 库存",style:"depotqty"),
grid.Column(style:"Edit",format:(item)=>Html.ActionLink("修改","Edit",new { id=item.id})),
grid.Column(style:"Delete",format:(item)=>Html.ActionLink("删除","Delete",new { id=item.id}))
)
);
}
CSS文件:
.Toolsa{border:1px solid #ECF2FD;border-collapse:collapse;}
.ToolsB{background:#D4DEE8;}
.Toolsa th,.ContactTB td{border:1px solid #03A5D1;}
. Toolsa tbody tr:hover{background:#E9E9E9;}
.Toolsa tfoot td{text-align:right;}
.Toolsa tfoot a{border:1px solid blue;padding:0 5px;}
table {table-layout:fixed;word-break:break-all;word-wrap:break-word;
}/*这里指定列宽固定,这个展示出来的数据列宽就会固定,而不是自适应了。*/
.matid{width:120px ;}
.MatName{width:200px;}
.MatDesc{width:280px;}
.Unit{width:100px;}
.Price{width:100px;}
.local{width:100px ;}
.scort{width:100px ;}
.depotqty{width:80px ;}
/*最后再自定义每个列的具体宽度*/
总结一下这个实现过程:
1,先将需要显示的字段建立一个类,
2,在控制器中使用LINQ查询实体数据类,将查询到的数据(分配?绑定?)到建立的实体类中,然后返回数据。
3,在页面中引用实体类,然后用表格展示数据。