在ASP.NET MVC3中使用EFCodeFirst 1.0

1. 新建项目

打开VS2010,选择 文件>新建>项目,新建ASP.NET MVC3 Web 应用程序,我这里把它命名为Blog。

image

2. 编写实体类

对于一个博客,一下几个类应该是必须的吧:

  • Post                             博客文章类
  • Comment                     文章评论类,和Post是一对多的关系
  • Category                     目录类,和Post是一对多的关系
  • Tag                             标签类,和Post是多对多的关系
  • FriendLink                  友情链接类

先不考虑管理员之类的东西。 在Model中依次添加上面的类。

image

namespace Blog.Models
{
    public class Post
    {
        public int ID { get; set; }
        public int CategoryID { get; set; }

        public string Title { get; set; }
        public string Summary { get; set; }
        public string Alias { get; set; }
        public string Content { get; set; }
        public DateTime CreateTime { get; set; }

        public Category Category { get; set; }
        public ICollection<Tag> Tags { get; set; }
        public ICollection<Comment> Coments { get; set; }
    }
}
namespace Blog.Models
{
    public class Comment
    {
        public int ID { get; set; }
        public int PostID { get; set; }
        public int Level { get; set; }
        public int ReplyTo { get; set; }

        public string UserName { get; set; }
        public string Email { get; set; }
        public string Website { get; set; }
        public string Content { get; set; }
        public DateTime CreateTime { get; set; }

    }
}
namespace Blog.Models
{
    public class Category
    {
        public int ID { get; set; }

        public string Name { get; set; }
        public string Alias { get; set; }
        public string Description { get; set; }
        public DateTime CreateTime { get; set; }

        public ICollection<Post> Posts { get; set; }
    }
}
namespace Blog.Models
{
    public class Tag
    {
        public int ID { get; set; }

        public string Name { get; set; }
        public string Alias { get; set; }
        public DateTime CreateTime { get; set; }

        public ICollection<Post> Posts { get; set; }
    }
}
namespace Blog.Models
{
    public class FriendLink
    {
        public int ID { get; set; }

        public string Name { get; set; }
        public string URL { get; set; }
        public string Description { get; set; }
        public DateTime CreateTime { get; set; }
    }
}

3. 添加EFCodeFirst

选择菜单栏的 工具 > Library Package Magager > Package Manager Console

image

在Package Manager Console中输入以下命令安装EFCodeFirst

PM> install-package efcodefirst 
image

安装成功后,VS会自动在你的项目中添加对EntityFramework的引用。

4. 配置

EFCodeFirst的配置是相当的简单,我们向Model中添加BlogDB类。

using System.Data.Entity;

namespace Blog.Models
{
    public class BlogDB : DbContext
    {
        public DbSet<Post> Posts { get; set; }
        public DbSet<Tag> Tags { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Comment> Comments { get; set; }
        public DbSet<FriendLink> FriendLinks { get; set; }
    }
}

打开web.config文件,添加链接字符串

<connectionStrings>
  <add name="BlogDB"
        connectionString="Server=.\;
          Database=Blog;Trusted_Connection=true" 
        providerName="System.Data.SqlClient" />
  <!--<add name="BlogDB"
        connectionString="Server=.\EXPRESS;
          Database=Blog;Trusted_Connection=true"
        providerName="System.Data.SqlClient" />-->
</connectionStrings>

注意,name属性的值为“BlogDB”这里和BlogDB这个类的类名保持一致。数据库名称为Blog(这个数据库现在并不存在)。

5. 小试牛刀

新建一个HomeController,添加如下代码。

using Blog.Models;

namespace Blog.Controllers
{
    public class HomeController : Controller
    {
        BlogDB _db = new BlogDB();
        //
        // GET: /Home/

        public ActionResult Index()
        {
            var posts = _db.Posts;
            return View(posts);
        }

    }
}

给Index Action创建一个View,如下图示:

image

添加完后就迫不及待的果断的奋力的按下F5吧,让我们看看都发生了什么!

image

网页显示了如下信息,不过这不是今天的重点,今天的重点是数据库。让我们打开数据库看看,里面发生了什么。

image

看吧,EF自动的为我们创建了数据库。

image

而且,EF足够聪明的为我们完成了Posts到Tags的多对多联系!!!我们程序中并没有和TagPosts表对应的Model,有的只是如下的两行代码

在Post类中

public ICollection<Tag> Tags { get; set; }

在Tag类中

public ICollection<Post> Posts { get; set; }

我们可以简单的使用如下的代码来获得标签“CSharp”中的所有文章。

var posts = _db.Tags
               .Where(t => t.Name == "CSharp")
               .Single()
               .Posts;

6. 修改Model后,自动更新数据表

当我们修改了Model后,运行网站时,会报错,因为EF现在不能把更新后的Model和旧数据表对应起来。为了使数据库随着Model的更新而更新,我们还要做以下的工作。

打开根目录下的Global.asax文件

添加如下命名空间(注意:EFCodeFirst 1.0 和 0.8 对于 DataBase 类所在的命名空间不同)

using System.Data.Entity;
using Blog.Models;

新建一个BlogDBInitializer类,使他继承DropCreateDatabaseIfModelChanges<BlogDB>,重写Seed函数。

public class BlogDBInitializer 
    : DropCreateDatabaseIfModelChanges<BlogDB>
{
    protected override void Seed(BlogDB context)
    {
        base.Seed(context);
            
        var links = new List<FriendLink>
        {
            new FriendLink{
                Name="NinoFocus.com",
                URL=@"http://ninofocus.com",
                Description="NinoFocus的个人博客"
            },
            new FriendLink{
                Name="NinoFocus at CNBlogs",
                URL=@"http://www.cnblogs.com/nizhuguo",
                Description="NinoFocus在博客园的博客"
            }
        };
        links.ForEach(l => context.FriendLinks.Add(l));
        context.SaveChanges();
    }
}

向Application_Start()中,添加如下代码

image

每次重建数据库后,数据库中的数据都是被清空。而Seed()函数的作用就是向新的数据库中添加以下初始化数据。

如上面的代码我添加了两个友情链接。

7. 写在最后

小弟也是刚学EF框架,可能还有很多地方我没注意到,或者说错了,请大家多多指教!

源码下载

Blog.rar

posted on 2011-04-11 12:16  nizhuguo  阅读(4492)  评论(49编辑  收藏  举报

导航