ef5 数据库操作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace efdemo
{
public class UserDal
{
static ZDEntities zz = new ZDEntities();
/// <summary>
/// lq查询说有
/// </summary>
public static void QueryListLq()
{
//var info = from p in zz.tests where p.ID >= 2 orderby p.ID descending select p;
var info = from p in zz.tests orderby p.ID descending select p;
foreach (var item in info)
{
Console.WriteLine("ID:" + item.ID + " " + "名称:" + item.name + " " + "年里:" + item.age);
}
}
/// <summary>
/// lmda查询
/// </summary>
public static void QueryListLmad()
{
//var info2 = zz.tests.Where<test>(p => p.ID >= 10).OrderByDescending(p => p.ID);
var info2 = zz.tests.ToList();
foreach (var item in info2)
{
Console.WriteLine("ID:" + item.ID + " " + "名称:" + item.name + " " + "年里:" + item.age);
}
}
/// <summary>
/// 查询所有
/// </summary>
public static void QuerylistSql()
{
string sql = "select * from test ORDER BY ID DESC";
var list = zz.Database.SqlQuery<test>(sql);
foreach (var item in list)
{
Console.WriteLine("ID:" + item.ID + " " + "名称:" + item.name + " " + "年里:" + item.age);
}
}
public static void Query()
{
List<test> list =zz.tests.Where(u => u.ID == ).ToList();
string b = null;
string c = null;
string d = null;
foreach(var a in list)
{
b = a.ID.ToString();
c = a.name.ToString();
d = a.age.ToString();
}
Console.WriteLine("id="+b);
Console.WriteLine("name="+c);
Console.WriteLine("age="+d);
}
/// <summary>
/// 修改
/// </summary>
public static void edit()
{
var test1 = new test()
{
ID = ,
name = "zhangsan"
};
zz.tests.Attach(test1);
zz.Entry<test>(test1).Property<string>(v => v.name).IsModified = true;
//Query();
//QuerylistSql();
//QueryListLq();
QueryListLmad();
}
/// <summary>
/// 删除
/// </summary>
public static void delte()
{
test stu = new test()
{
ID =
};
var list = zz.tests.Where(u => u.ID == );
if (list.Count() > && list != null)
{
foreach (var ll in list)
{
zz.tests.Remove(ll);
}
}
zz.SaveChanges();
}
public static void Add()
{
try
{
test user = new test()
{
name="",
age=,
};
//ZDEntities zz = new ZDEntities();
zz.tests.Add(user);
zz.SaveChanges();//保存到数据库
}
catch(Exception ex)
{
throw new Exception("错误", ex);
}
}
}
}
class Program
{
static void Main(string[] args)
{
//UserDal.Add();
//Console.WriteLine("保存成功");
//UserDal.Query();
UserDal.edit();
Console.WriteLine("修改成功");
Console.Read(); }
}

  

上一篇:Win7路由器设置过程


下一篇:《数据结构与算法 C语言版》—— 2.2线性表的顺序表示与实现