EF Code-First CRUD操作
网上很多的教程都是跟MVC3绑在一起来讲解的,如果我们抛开MVC3,该如何使用呢?
首先新建一个控制台应用程序,我们把它命名为:EFCodeFirst-Books
第二步,添加EntityFramework的引用。
不要说你还不回使用NuGet,如果真的不会就去问度娘。在NuGet 控制台输入Install-Package EntityFramework,NuGet会为我们引用最新发布的EF版本,目前的版本是4.3。
第三步,添加实体类。
我新建了一个Models文件夹,在里面添加了Book类,类的定义如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace EFCodeFirst_Books.Models { public class Book { public int BookID { get; set; } public string BookName { get; set; } public string Author { get; set; } public string Publisher { get; set; } public decimal Price { get; set; } public string Remark { get; set; } } }
因为是测试,我只添加了一个类。
第四步,添加DbContext类。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace EFCodeFirst_Books.Models { public class AppDbContext : DbContext { public DbSet<Book> Books { get; set; } } }
第五步,检查你的数据库连接
如果你安装了SqlExpress,EF会自动的将连接指向SqlExpress,此处就不需要修改了。
如果你需要改到别的地方,需要修改一下数据库连接:
<entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"> <parameters> <parameter value="Data Source=.;Initial Catalog=EFCodeFirst_Books;Integrated Security=True" /> </parameters> </defaultConnectionFactory> </entityFramework>
我这里指向的是本机的数据库,采用集成的安全验证。
第六步,开始你的CRUD操作
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EFCodeFirst_Books.Models; namespace EFCodeFirst_Books { class Program { static void Main(string[] args) { Book book = new Book() { BookName = "C#高级编程", Price = 151.8M, Publisher = "清华大学出版社", Author = "Wrox", }; AppDbContext dbContext = new AppDbContext(); dbContext.Books.Add(book); dbContext.SaveChanges(); var booksQuery = from b in dbContext.Books select b; List<Book> booksList = booksQuery.ToList(); book = booksList[0]; book.Price = 203M; dbContext.SaveChanges(); dbContext.Books.Remove(book); } } }
本文作者:拓荒者IT
本文链接:https://www.cnblogs.com/youring2/archive/2012/05/23/2514442.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
📌做了个微信公众号【拓荒者IT】,分享各种技术干货,新内容首发到公众号,欢迎关注❤️
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2011-05-23 枚举值转换(字符串转换为枚举和整数转换为枚举)
2010-05-23 为Windows Live Writer写一个简单的插件