怎么使用DataBase First模式实现数据库的增删改查
导读:本文共1968.5字符,通常情况下阅读需要7分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 一、新增数据新增一个Student,代码如下:staticvoidAdd(){using(StudentSystemEntitiesdbContext=newStudentSystemEntities()){//定义Student对象Studentstu=newStudent(){StudentName="花千骨",Sex=&... ...
音频解说
目录
(为您整理了一些要点),点击可以直达。一、新增数据
新增一个Student,代码如下:
staticvoidAdd(){using(StudentSystemEntitiesdbContext=newStudentSystemEntities()){//定义Student对象Studentstu=newStudent(){StudentName="花千骨",Sex="女",Age=3422,Major="舞蹈专业",Email="2345678911@qq.com"};//将EF执行的SQL语句输出到控制台dbContext.Database.Log+=p=>Console.WriteLine(p);//只是内存上面的操作dbContext.Students.Add(stu);//保存的数据库dbContext.SaveChanges();Console.WriteLine("保存成功");}}
在Main()方法里面调用Add()方法,结果:
查看数据库结果:
从上面的两个截图中可以看出数据新增成功。
二、查询数据
查询StudentName是唐僧的学生信息并输出:
staticvoidQuery(){using(StudentSystemEntitiesdbContext=newStudentSystemEntities()){List<Student>list=dbContext.Students.Where(p=>p.StudentName=="唐僧").ToList<Student>();list.ForEach(p=>{Console.WriteLine("姓名:"+p.StudentName+",年龄:"+p.Age+",专业:"+p.Major+",邮箱:"+p.Email);});}}
在Main()方法里面调用Query(),结果:
三、修改数据
修改StudentName为花千骨的学生年龄:
staticvoidEdit(){using(StudentSystemEntitiesdbContext=newStudentSystemEntities()){//将EF执行的SQL语句输出到控制台dbContext.Database.Log+=p=>Console.WriteLine(p);//查询要修改的数据,FirstOrDefault表示查询到的第一条数据Studentstudent=dbContext.Students.Where(p=>p.StudentName=="花千骨").FirstOrDefault();//保存修改student.Age=234;dbContext.SaveChanges();Console.WriteLine("修改成功");}}
结果:
查看数据库数据:
四、删除数据
删除新添加的数据:
staticvoidDelete(){using(StudentSystemEntitiesdbContext=newStudentSystemEntities()){//将EF执行的SQL语句输出到控制台dbContext.Database.Log+=p=>Console.WriteLine(p);//先查询然后在删除Studentstu=newStudent(){StudentID=18};//附加到集合中dbContext.Students.Attach(stu);//删除的SQL语句是根据stu的StudentID生成的dbContext.Students.Remove(stu);//保存dbContext.SaveChanges();Console.WriteLine("删除成功");}}
结果:
查看数据库:
数据删除成功。
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:
怎么使用DataBase First模式实现数据库的增删改查的详细内容,希望对您有所帮助,信息来源于网络。