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);
        }
    }
}
posted @ 2012-05-23 11:02  拓荒者FF  阅读(2951)  评论(0编辑  收藏  举报