dhl:vs2010 -EF4.0 数据层: 通过反射返回泛型的工厂

最近用vs2010做项目,想到了数据层Linq To Entity的实现和以后的扩展,想以接口的形式实现。

总体架构图:

dhl:vs2010 -EF4.0 数据层: 通过反射返回泛型的工厂_第1张图片

数据层Data:

普通的数据操作数据层:

接口IUserRepository:

 

  
  
public interface IUserRepository
{
IList
< UserAccount > GetCommonInterestsUser( int UIN);
void AddUser();
....
}

接口的实现类UserRepository:

public class UserRepository:IUserRepository
    {
        private TaoXueDBEntities _TaoXueDBEntities = new TaoXueDBEntities();
        public IList<UserAccount> GetCommonInterestsUser(int UIN)
        {
            return _TaoXueDBEntities.GetMyLike(UIN).ToList();
        }
    }

 

工厂:

 public class RepositoryFactory
    {
        private readonly IDictionary<String, Object> factory = new Dictionary<String, Object>();
        /// <summary>
        /// 获取用户Repository 
        /// </summary>
        /// <returns>用户仓储接口</returns>
        public IUserRepository GetUserRepository()
        {
            string className = "Taoxue.Data.UserRepository";
            if (factory.ContainsKey(className)) return factory[className] as UserRepository;
            IUserRepository repo = Activator.CreateInstance(Type.GetType(className)) as IUserRepository;
            factory.Add(className, repo);
            return repo;
        }
}
 

 

泛型的数据接口:

 

代码
   
   
public interface IRepository < T > where T : class
{
int Add(T entity);
int Count(ICriteria criteria);
int Delete(T entity);
int ExecuteStoreCommand( string commandText, params ObjectParameter[] paramete);
ObjectResult
< T > ExecuteStoreQuery( string commandText, params ObjectParameter[] paramete);
IList
< T > Find(ICriteria criteria, int page, int pageSize, OrderBy orderExpr);
IList
< T > FindAll();
IList
< T > FindAll(Func < T, bool > exp);
ObjectSet
< T > FindQuerySet() ;
ObjectContext GetObjectContext();
ObjectQuery
< T > GetQuery( string query, params ObjectParameter[] parameter);
int SaveChanges();
int Update(T entity);
}

 

泛型的实现类:

 public class Repository<T> : IRepository<T> where T : class
    {

        private ObjectContext _objectContext = null;
        #region objectContext
        /// <summary>
        /// 获得提供用于查询和使用对象形式的实体数据功能
        /// </summary>
        /// <returns>数据库上下文</returns>
        public virtual ObjectContext GetObjectContext()
        {
            return new TaoXueDBEntities();
        }
        #endregion


        public Repository()
        {
        }
        /// <summary>
        /// 按条件查询所有对象
        /// </summary>
        /// <param name="exp">表达式</param>
        /// <returns>查询结果</returns>
        public IList<T> FindAll(Func<T, bool> exp)
        {
            using (var objectContext = GetObjectContext())
            {
                var result = objectContext.CreateObjectSet<T>().Where(exp).ToList();
                return result;
            }
        }
        /// <summary>
        /// 返回所有对象
        /// </summary>
        /// <returns></returns>
        public IList<T> FindAll()
        {
            using (var objectContext = GetObjectContext())
            {
                var v = objectContext.CreateObjectSet<T>();
                return v.ToList();
            }
        }
        /// <summary>
        /// 获取数据集实例,用于查询,修改,添加,删除
        /// </summary>
        /// <returns></returns>
        public ObjectSet<T> FindQuerySet()
        {
            if (_objectContext == null)
            {
                _objectContext = GetObjectContext();
            }

            var result = _objectContext.CreateObjectSet<T>();
            return result;
        }

        /// <summary>
        /// ESQL查询,绑定了EF框架
        /// </summary>
        /// <param name="query">ESQL语句</param>
        /// <param name="parameter">参数(可选)</param>
        /// <returns></returns>
        public ObjectQuery<T> GetQuery(string query, params ObjectParameter[] parameter)
        {
            using (var objectContext = GetObjectContext())
            {
                var result = objectContext.CreateQuery<T>(query, parameter);
                return result;
            }
        }
        /// <summary>
        /// 执行数据源语句(如SQL),返回影响的行数
        /// </summary>
        /// <param name="commandText">查询语句</param>
        /// <param name="parameter">参数(可选)</param>
        /// <returns></returns>
        public int ExecuteStoreCommand(string commandText, params ObjectParameter[] paramete)
        {
            if (string.IsNullOrEmpty(commandText))
            {
                return -1;
            }
            using (var objectContext = GetObjectContext())
            {
                var result = objectContext.ExecuteStoreCommand(commandText, paramete);
                return result;
            }
        }
        /// <summary>
        /// 执行数据源查询语句(如SQL),获得数据查询列表
        /// </summary>
        /// <param name="commandText">查询语句</param>
        /// <param name="parameter">参数(可选)</param>
        /// <returns></returns>
        public ObjectResult<T> ExecuteStoreQuery(string commandText, params ObjectParameter[] paramete)
        {
            using (var objectContext = GetObjectContext())
            {
                var result = objectContext.ExecuteStoreQuery<T>(commandText, paramete);
                return result;
            }
        }
       
        /// <summary>
        /// 添加对象
        /// </summary>
        /// <param name="entity"></param>
        /// <returns>修改成功的对象数</returns>
        public int Add(T entity)
        {
            using (var objectContext = GetObjectContext())
            {
                objectContext.CreateObjectSet<T>().AddObject(entity);
                var result = objectContext.SaveChanges();
                return result;
            }
        }
        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="entity">将被删除的对象</param>
        /// <returns>删除的数量</returns>
        public int Delete(T entity)
        {
            //objectContext.Attach(entity);            
            using (var objectContext = GetObjectContext())
            {
                try
                {
                    objectContext.CreateObjectSet<T>().Attach(entity);
                    objectContext.CreateObjectSet<T>().DeleteObject(entity);
                }
                catch (Exception e)
                {
                    //todo:log it e
                }
                var result = objectContext.SaveChanges();
                return result;
            }
        }
        /// <summary>
        /// 提交所有修改
        /// </summary>
        public int SaveChanges()
        {
            if (_objectContext != null)
                return _objectContext.SaveChanges();
            else
                return -1;
        }
        /// <summary>
        /// 更新对象
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update(T entity)
        {
            using (var objectContext = GetObjectContext())
            {
                objectContext.CreateObjectSet<T>().Attach(entity);                  
                //objectContext.SetAllModified(entity);
                objectContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);//EF4 新语法
                try
                {
                    var result = objectContext.SaveChanges();
                    return result;
                }
                catch (OptimisticConcurrencyException e)
                {
                    objectContext.Refresh(RefreshMode.ClientWins, entity); // Last in wins
                    //logger.Write(e);
                    var result = objectContext.SaveChanges();
                    return result;
                }
            }

            //using (var ctx = new AdventureWorksEntities())
            //{
            //    // 先 ApplyChanges() 再 ChangeObjectState(), ChangeRelationshipState()
            //    ctx.ProductCategories.ApplyChanges(category);
            //    ctx.ObjectStateManager.ChangeObjectState(category, EntityState.Modified);

            //    return ctx.SaveChanges();
            //}
        }
}

 

 

工厂RepositoryFactory:

 

代码
   
   
public class RepositoryFactory
{
private readonly IDictionary < String, Object > factory = new Dictionary < String, Object > ();

#region RepositoryFactory 为单例
/// <summary>
/// RepositoryFactory 为单例模式
/// </summary>
private static RepositoryFactory Instance;
private RepositoryFactory()
{
}
/// <summary>
/// 获取Repository工厂实例
/// </summary>
/// <returns> Repository工厂实例 </returns>
public static RepositoryFactory GetInstance()
{
if (Instance == null ) Instance = new RepositoryFactory();
return Instance;
}
#endregion

#region 工厂方法:通过反射返回泛型数据操作接口的实现类
/// <summary>
/// 获取实体类的Repository的接口IRepository
/// </summary>
/// <typeparam name="T"> 实体Entity </typeparam>
/// <returns> 泛型IRepository </returns>
public IRepository < T > GetRepository < T > () where T : class
{
Type t
= typeof (T);
if (factory.ContainsKey( " Repository " + t.FullName)) return factory[ " Repository " + t.FullName] as IRepository < T > ;
string className = " Taoxue.Data.Repository`1 " ;
className
+= " [[ " + t.FullName + " , " + t.Assembly.FullName + " ]] " ;
Type type
= Type.GetType(className);
IRepository
< T > repo = Activator.CreateInstance(type) as IRepository < T > ;
factory.Add(
" Repository " + t.FullName, repo);
return repo;
}
#endregion

#region 工厂方法:通过反射返回其他数据操作接口的实现类
/// <summary>
/// 获取用户Repository
/// </summary>
/// <returns> 用户仓储接口 </returns>
public IUserRepository GetUserRepository()
{
string className = " Taoxue.Data.UserRepository " ;
if (factory.ContainsKey(className)) return factory[className] as UserRepository;
IUserRepository repo
= Activator.CreateInstance(Type.GetType(className)) as IUserRepository;
factory.Add(className, repo);
return repo;
}

public ITaokeRepository GetTaoxueRepository()
{
const string className = " Taoxue.Data.TaokeRepository " ;
if (factory.ContainsKey(className)) return factory[className] as ITaokeRepository;
var repo
= Activator.CreateInstance(Type.GetType(className)) as ITaokeRepository;
factory.Add(className, repo);
return repo;
}
#endregion
}

 

  上层业务的调用:

            IRepository<Lesson> repository = RepositoryFactory.GetInstance().GetRepository<Lesson>();
            IList<Lesson> listAll = repository.FindAll();
            return listAll;

 

你可能感兴趣的:(VS2010)