在开始之前,先声明一下,写本系列教程是参照
韩迎龙(Kencery)http://www.cnblogs.com/hanyinglong/category/399820.html 的博客,然后把我的思想融入到这个框架中,如有任何版权问题请给我留言。
上一篇文章主要介绍了一下整体框架的设计,这个设计现在还是很粗糙的,会在以后的文章中继续完善。
切入正题,这一章主要介绍Model层的设计,用的是EntityFramework,由于项目初期可能数据库字段经常发生改变,所以用的是CodeFirst。
在Model项目中新建User类,内容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Model
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Pwd { get; set; }
}
}
在Model项目中新建Role类,内容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Model
{
public class Role
{
public int Id { get; set; }
public int RoleValue { get; set; }
public string RoleName { get; set; }
}
}
暂时这两个类的字段定义如此,随着项目的完善,这两个类的字段会有所变化。
现在,该是EntityFramework出场的时候了,
一.建立数据库上下文类(在Model类库中建立HelloMVCDataContext.cs),我理解数据库上下文就是,把数据库的所有表映射到这个类中,操作这个类就像操作数据库字段一样。具体代码如下
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
namespace Model
{
public class HelloMVCDataContext : DbContext
{
public DbSet<User> UserDb { get; set; }
public DbSet<Role> RoleDb { get; set; }
}
}
需要注意一下,需要引用System.Data.Entity.dll 和EntityFramework.dll我用的是EntityFramework5.0 。
二.在Web.config中配置数据库上下文的连接字符串,具体如下:
<connectionStrings>
<add name="HelloMVCDataContext"
connectionString="Data Source=(LocalDb)\v11.0;
Initial Catalog=HelloMVCDataContext;
Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\HelloMVCDataContext.mdf"
providerName="System.Data.SqlClient" />
</connectionStrings>
三.测试下code first 是否配置正确,在Ocean.HelloMVC项目中,Controllers文件夹中HomeController类的Index方法中添加代码,具体如下
public ActionResult Index()
{
Model.HelloMVCDataContext db = new Model.HelloMVCDataContext();
db.RoleDb.ToList();
ViewBag.Message = "修改此模板以快速启动你的 ASP.NET MVC 应用程序。";
return View();
}
四.运行程序,如果没有报错。证明配置正确,也可以查看 Ocean.HelloMVC项目中App_Data文件夹下时候已经生成配置的数据库。
今天的CodeFirst就暂时到这里,下一章会讲解IDAL和DAL层。