跟我学MVC系列(Repository模式、LINQ、EF、IOC框架Castle、JQuery、AJAX)(一)数据库建模 在《企业架构模式》中,译者将Repository翻译为资源库。给出如下说明: 在《领域驱动设计:软件核心复杂性应对之道》中,译者将Repository翻译为仓储,给出如下说明: 使用该模式的最大好处就是将领域模型从客户代码和数据映射层之间解耦出来。 ”摘自http://www.cnblogs.com/carysun/archive/2009/03/20/repository.html具体请各位百度一下吧。 现在开始创建所需的文件夹,“Models”文件夹是提供所有实体类的接口,比如“用户”、“账目”等,以及对这些实体类的所有操作功能(增删改查),于是我们首先在“Models”文件夹下创建三个接口,它们分别是"IUser" "IAccount" "IAccountType"作为用户类、账目类和账目类型类的接口,代码如下: using System; 以上就是三个接口啦,具体内容一看明了.OK,现在还在要Models文件夹下建二个文件夹,它们分别是“User” "Account",这两个文件夹下主要是具体功能的实现。Models里面的东东是不与数据库直接打交道的,我们使用Repository模式来提供与数据库直接打交道的增删查改的操作,Models直接使用Repository提供的基本功能。好了,我们先把Models放在这儿不管,下面来设置Repository模式,首先创建一个Repository文件夹(与Models平级),如下图:using System.Collections.Generic; using System.Linq; using System.Text; namespace PBAccount.Models { public interface IAccount { Guid AccountID { get; set; } IUser user { get; set; } bool InOrOut { get; set; } float Amount { get; set; } IAccountType AccountType { get; set; } DateTime Time { get; set; } AccountStatus Status { get; set; } string Detail { get; set; } } /// <summary> /// 账目可见性 /// </summary> public enum AccountStatus { /// <summary> /// 私有 /// </summary> personal=0, /// <summary> /// 公开 /// </summary> open } } using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PBAccount.Models { public interface IAccountType { Guid AccountTypeID { get; set; } string AccountTypeName { get; set; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PBAccount.Models { public interface IUser { Guid UserID { get; set; } string LoginName { get; set; } string Name { get; set; } bool Sex { get; set; } DateTime BirthDay { get;set;} string Profession { get; set; } int Role { get; set; } } } ,要与数据库打交道,我们就想到了EF这个ORM,关于EF,请参考:http://www.cnblogs.com/xray2005/archive/2009/05/07/1452033.html , 打开“服务器资源管理器”,建立与我们创建的数据库的连接,如下图: ,然后,在“Repository”文件夹下面添加“ADO.NET Entity Data Model”,我们命名为“AccountEDM”, 然后选择“从数据库生成”,把我们建立的三个表全选,系统就自动生成了一个EF,如下图: 这一篇就介绍到这儿,下一篇我们具体介绍Repository模式与EF结合在ASP.NET MVC中的应用。 欢迎批评指正。 |
|