MVC+Linq+EF笔记

using (DataContext ctx = new DataContext())
{
/*foreach (var item in ctx.employees)
{
ViewData["Name"] = item.Name;
}
*/
//------------------------------------------
/*var employees = from emp in ctx.employees
where emp => emp.Age == 22 && emp.ID == "123456781"
select emp;
//上边转化
var employees = ctx.employees.Where(emp => emp.Age == 22 && emp.ID == "123456781");
foreach (var item in employees)
{
ViewData["Name"] = item.Name;
}--------------------------------------------*/
/*---------------------------------------
* var employees = from emp in ctx.employees
where emp.Age == 22 && emp.ID == "123456781"
select emp.Name;//查询单个字段

var employees = ctx.employees.Where(emp => emp.Age == 22 && emp.ID == "123456781")
.OrderBy(emp => emp.ID)
.Select(emp => emp.Name);//查询单个字段
//---------------------------------------------------

var employees2 = from emp in ctx.employees
where emp.Age == 21
select new { emp.Age, emp.Name };//查询多个字段*/
/*var employees2 = ctx.employees
.Where(emp => emp.Age == 21)
.OrderBy(emp => emp.Age)
.Select(emp => new { emp.Name, emp.Age });//查询多个字段
//----------------------------------------------
/不管怎样都要用foreach、
foreach (var item in employees)
{
ViewData["single"] = item;//因为它查出来是单个字段,所以直接输出,不用点了
}
foreach (var item in employees2)
{
ViewData["doubleAge"] = item.Age;
ViewData["doubleName"] = item.Name;//他很智能的。
}
//------------------------------------

var employees = ctx.employees.Find("123456781");
if (employees != null)
{
ViewData["df"] = employees;
}

//加载数据到内存中,加载完了就可以用Local了
ctx.employees.Load();
var employees = from employee in ctx.employees.Local select employee;
foreach (var item in employees)
{
ViewData["fsdf"] = item;
}
//inclue 贪婪查询。
var employees = ctx.employees.Include(p => p.department);
foreach (var item in employees)
{
ViewData["dep"] = item.department.DepName;
ViewData["empName"] = item.Name;
}*/

var employees = ctx.employees.Include(emp=>emp.department).ToList();//查询列表
ViewData.Model = employees;
return View();

 

 

外键数据保存:

public ActionResult AddHandler(int droplist, Employee emp)
{
using (DataContext dbcontext=new DataContext ())
{
int did = droplist;
Department dep = new Department();
dep = dbcontext.dempartments.Find(did);//先找到外键实体
emp.department = dep;//因为emp中外键是一个实体,所以你要给实体,不能只给ID外键。
dbcontext.employees.Add(emp);
dbcontext.SaveChanges();

return RedirectToAction("List");
}
}


}

posted @ 2015-06-01 11:26  caijinhao  阅读(237)  评论(0编辑  收藏  举报