两种底层数据层操作时的架构方式
第一种,效率较高,也是很多开源项目用的方法,使用了贬型
第二种,比较基础,安全性比较高,讲究面向接口的编程,我所以实体对象都继承自统一的接口
#region 数据底层操作架构一
/// <summary>
/// 用户实体
/// </summary>
public class User
{
public string UserName { get; set; }
public int Age { get; set; }
}
public class UserRepository : IRepository<User>
{
#region IRepository<User> Members
public User Get(object id)
{
User user = new User { };
return user;
}
public IQueryable<User> GetList()
{
throw new NotImplementedException();
}
#endregion
}
/// <summary>
/// 数据操作统一接口,它提供一个贬型作为参数,但要求贬型必须是类
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IRepository<T> where T : class
{
/// <summary>
/// 获取实体
/// </summary>
/// <param name="id">主键</param>
/// <returns></returns>
T Get(object id);
/// <summary>
/// 得到列表
/// </summary>
/// <returns></returns>
IQueryable<T> GetList();
}
#endregion
#region 数据底层操作架构二
class User2 : IDataEntity
{
public string UserName { get; set; }
public int Age { get; set; }
}
/// <summary>
/// 数据实体统一接口
/// </summary>
public interface IDataEntity
{
}
/// <summary>
/// 数据操作统一接口
/// </summary>
public interface IRepository2
{
/// <summary>
/// 获取实体
/// </summary>
/// <param name="id">主键</param>
/// <returns></returns>
IDataEntity Get(object id);
/// <summary>
/// 得到列表
/// </summary>
/// <returns></returns>
IQueryable<IDataEntity> GetList();
}
public class User2Repository : IRepository2
{
#region IRepository2 Members
public IDataEntity Get(object id)
{
throw new NotImplementedException();
}
public IQueryable<IDataEntity> GetList()
{
throw new NotImplementedException();
}
#endregion
}
#endregion