首先,保证已经完成数据库以及Database First模式建模
增删查改
/// <summary>
/// 添加
/// </summary>
private static void Add()
{
Admin admin = new Admin();
admin.UName = Console.ReadLine();
admin.Pwd = Console.ReadLine();
using (MeixinEntities1 db=new MeixinEntities1())
{
db.Admin.Add(admin);
db.SaveChanges();
Console.WriteLine("管理员信息添加成功!");
}
}
/// <summary>
/// 删除
/// </summary>
private static void Delete()
{
Show();// 查询
int id = Convert.ToInt32(Console.ReadLine());// 获取编号
using (MeixinEntities1 db=new MeixinEntities1())
{
var data = db.Admin.FirstOrDefault(p => p.ID == id);
db.Admin.Remove(data);
db.SaveChanges();
}
}
/// <summary>
/// 查询
/// </summary>
private static void Show()
{
using (MeixinEntities1 db=new MeixinEntities1())
{
var data = db.Admin.ToList();
foreach (var item in data)
{
Console.WriteLine("{0}\t{1}\t{2}\t",item.ID,item.UName,item.Pwd);
}
}
}
/// <summary>
/// 修改
/// </summary>
private static void Edit()
{
Show();// 查询
int id = Convert.ToInt32(Console.ReadLine());// 获取编号
using (MeixinEntities1 db=new MeixinEntities1())
{
var data = db.Admin.FirstOrDefault(p => p.ID == id);
if (data != null)// 判断id是否存在
{
string pwd = Console.ReadLine();
if (!String.IsNullOrEmpty(pwd))
{
data.Pwd = pwd;
}
}
db.SaveChanges();
}
}
注:Using语句可自动释放数据库上下文对象占用的数据库资源
当然,这种增删查改是比较繁琐的,并且结构比较单一,下面介绍一种扩展的批量操作方法,还比较节省资源消耗
NuGet下载
Z.EntityFramework.Extensions
EntityFramework.Extended
/// <summary>
/// 添加多条信息
/// </summary>
private static void Show()
{
using (MeixinEntities1 db = new MeixinEntities1())
{
var admins = new List<Admin>()
{
new Admin(){UName="zhangsan",Pwd="111"},
new Admin(){UName="lisi",Pwd="111"},
new Admin(){UName="wangwu",Pwd="111"},
new Admin(){UName="zhaoliu",Pwd="111"}
};
db.BulkInsert(admins);
db.SaveChanges();
}
}
/// <summary>
/// 批量修改信息
/// </summary>
private static void Edit()
{
using (MeixinEntities1 db = new MeixinEntities1())
{
Admin admin = new Admin();
db.Admin.Update(p=> new Admin { Pwd="111"});
db.SaveChanges();
}
}
注意!!我这里只是测试案例,大家做项目切记切记别忘了where,更新和删除最为危险!!!