2012年3月2日星期五

EF Code First构架~Data层的实现

EF的Code First开始模式时,在设计Data层与Data First模式稍微有些不同,它主要有数据库类,数据库操作基类,数据通用操作接口和数据通过操作实现组成,每个类有自己的用途,先看一下最简单的结构:

image

DataContext是EF的数据库对象类型,它里面的代码构架了我们的数据表对象

 public class DataContext : DbContext, IDataContext    {        #region Properties        /// <summary>        /// 得ì?到ì?UserBase结¨¢果?集?¥        /// </summary>        public IDbSet<UserBase> UserBases { get; private set; }        /// <summary>        /// 得ì?到ì?UserInfo结¨¢果?集?¥        /// </summary>        public IDbSet<UserInfo> UserInfos { get; private set; }        /// <summary>        /// 得ì?到ì?Category结¨¢果?集?¥        /// </summary>        public IDbSet<Category> Categorys { get; private set; }        #endregion        #region Constructors        public DataContext()            : base(DataContext.GetConnectionString())        {            InitDbSets();        }        public DataContext(string cs)            : base(cs)        {            InitDbSets();        }        #endregion        #region  Private Methods        private void InitDbSets()        {            UserBases = this.Set<UserBase>();            UserInfos = this.Set<UserInfo>();            Categorys = this.Set<Category>();            Init();//数oy据Y库a与??DBContext依°¨¤附?方¤?式o? ?        }        /// <summary>        /// 得ì?到ì?数oy据Y连¢?接¨?串??        /// </summary>        /// <returns></returns>        private static string GetConnectionString()        {            string conn;            if (System.Diagnostics.Debugger.IsAttached)            {                conn = VConfigs.WebInfoConfig.Get_Config().DevsSqlConn;            }            else            {                conn = VConfigs.WebInfoConfig.Get_Config().ReleaseSqlConn;            }            return conn;        }        /// <summary>        /// 根¨′据Y传??入¨?的ì?类¤¨¤型¨a,ê?进?行DDBContext出?始o?化?¥        /// </summary>        /// <param name="InitType"></param>        private static void SetInitializer(InitializerTypes InitType)        {            switch (InitType)            {                case InitializerTypes.Standard:                    Database.SetInitializer(new CreateDatabaseIfNotExists<DataContext>());                    break;                case InitializerTypes.ReCreateAlways:                    Database.SetInitializer(new DropCreateDatabaseAlways<DataContext>());                    break;                case InitializerTypes.ReCreateByChange:                    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DataContext>());                    break;                default:                    break;            }        }        /// <summary>        /// DBContext初?始o?化?¥方¤?法¤?§        /// </summary>        private static void Init()        {            Database.DefaultConnectionFactory = new SqlConnectionFactory();            if (System.Diagnostics.Debugger.IsAttached)            {                DataContext.SetInitializer(InitializerTypes.ReCreateByChange);            }            else            {                DataContext.SetInitializer(InitializerTypes.Standard);            }        }        #endregion        /// <summary>        /// 数oy据Y库a建?§立¢?é时o?à执??行D        /// </summary>        /// <param name="modelBuilder"></param>        protected override void OnModelCreating(DbModelBuilder modelBuilder)        {         }    }

其中dataBase就是数据库操作基类,主要实现创建dbcontext对象和对修改进行统一提交的作用

/// <summary>    /// 数oy据Y库a基¨′类¤¨¤    /// </summary>    public abstract class DataBase    {        #region 单죤件t模?ê式o?创???建?§一°?个?类¤¨¤对?象¨?        /// <summary>        /// 数oy据Y源??对?象¨?        /// </summary>        private static DataContext _db = null;        protected static DataContext CreateInstance()        {            if (_db == null)                _db = new DataContext();            return _db;        }        #endregion        /// <summary>        /// 数oy据Y库a访¤?问¨o对?象¨?        /// </summary>        protected DataContext Db = CreateInstance();        /// <summary>        /// 统a3一°?提?¨¢交?动?¥作á??        /// </summary>        protected virtual void SubmitChanges()        {            try            {                Db.SaveChanges();            }            catch (Exception ex)            {                throw;            }        }    }

而数据操作统一接口主要实现对数据库的CURD操作,代码一般是这样(与其它构架大同小异)

 /// <summary>    /// 通a?§用??数oy据Y库a访¤?问¨o接¨?口¨2    /// </summary>    public interface IRepository<TEntity> where TEntity : Entity.BaseEntity    {        /// <summary>        /// 根¨′据Y数oy据Y库a实o|ì体??-a》?¤更¨1新?记?录?        /// </summary>        /// <param name="entity"></param>        void Update(TEntity entity);         /// <summary>        /// 根¨′据Y数oy据Y库a实o|ì体??-a》?¤[批¨2量¢?]更¨1新?记?录?        /// </summary>        /// <param name="entity"></param>        void Update(IList<TEntity> list);               /// <summary>        /// 根¨′据Y数oy据Y库a实o|ì体??-a》?¤插?入¨?记?录?        /// </summary>        void Insert(TEntity entity);        /// <summary>        /// 根¨′据Y数oy据Y库a实o|ì体??-a》?¤[批¨2量¢?]插?入¨?记?录?        /// </summary>        void Insert(IList<TEntity> list);        /// <summary>        /// 根¨′据Y数oy据Y库a实o|ì体??-a》?¤插?入¨?记?录?并?é返¤|ì回?刚?刚?立¢?é即??插?入¨?的ì?状á??态??视o¨?图a?        /// </summary>        TEntity InsertGetIDENTITY(TEntity entity);        /// <summary>        /// 根¨′据Y数oy据Y库a实o|ì体??-a》?¤多¨¤主??键¨1,删|?除y有?D多¨¤个?参?数oy控?制?的ì?对?象¨?        /// </summary>        /// <param name="oArr"></param>        void Delete(TEntity entity);        /// <summary>        /// 返¤|ì回?默?认¨?结¨¢果?集?¥        /// </summary>        /// <returns></returns>        IQueryable<TEntity> GetModel();        /// <summary>        /// 根¨′据Y主??键¨1返¤|ì回?实o|ì体??        /// </summary>        /// <returns></returns>        TEntity GetModelById(int id);    }

事实上我们真实的datacontext对象在实现开发中只有Data本层可见,而对于业务层和UI层是不被容许访问的,当然这也是保存原数据对象及方便扩展和维护的一种作法。


EF Code First构架~Data层的实现

TAG: