【发布时间】:2011-01-06 21:34:40
【问题描述】:
我已经实现了存储库模式以通过 Linq2Sql ORM 访问数据库数据:
public abstract class RepositoryBase<T, TDb> : IRepository<T>
where T : IEntity
where TDb : class, IDbEntity, new()
{
protected RepositoryBase(IUnityContainer container)
{
_container = container;
_context = _container.Resolve<CMCoreDataClassesDataContext>();
}
public IQueryable<T> GetAll()
{
return GetTable().Select(GetConverter());
}
protected abstract Table<TDb> GetTable();
protected abstract Expression<Func<TDb, T>> GetConverter();
protected CMCoreDataClassesDataContext Context { get { return _context; } }
private readonly IUnityContainer _container;
private readonly CMCoreDataClassesDataContext _context;
}
以下是特定存储库实现的示例:
public class CustomerProductRepository
: RepositoryBase<ICommonCustomerProduct, CMCoreDAL.DbData.CustomerProduct>
{
protected override Table<CMCoreDAL.DbData.CustomerProduct> GetTable()
{
return Context.CustomerProducts;
}
protected override Expression<Func<CMCoreDAL.DbData.CustomerProduct, ICommonCustomerProduct>> GetConverter()
{
return dbEntity => dbEntity.ProdId == (int)ProductType.ProductTypeEnum.CommonProduct
? new CommonCustomerProduct
{
UnityContainer = UnityContainer,
InstanceId = dbEntity.InstanceId,
CustomerId = dbEntity.CustomerID,
StatusCode = dbEntity.StatusCode,
DeviceLicenses = dbEntity.DeviceLicenses,
ServerLicenses = dbEntity.ServerLicenses,
}
: new SpecificCustomerProduct()
{
UnityContainer = UnityContainer,
InstanceId = dbEntity.InstanceId,
CustomerId = dbEntity.CustomerID,
StatusCode = dbEntity.StatusCode,
UserLicenses = dbEntity.DeviceLicenses,
}
;
}
这里SpecificCustomerProduct继承自CommonCustomerProduct。
提供的源代码显示了数据库中的记录如何根据实例类型映射到不同的实例。这些类有很多共同的领域,只有少数是不同的。
我对此代码有 2 个顾虑:
- 一些重复的赋值操作;
-
可读性低:为了添加更多具体的类,我需要制作不可读的链:
return dbEntity => dbEntity.ProdId == iType1 ? new Type1 { ... assignments } : { dbEntity.ProdId == iType2 ? new Type2 { ... assignments } : new Type3 { ... assignments } }
有没有更好的方法来实现这种模式的“类型相关”映射?
【问题讨论】:
标签: c# linq-to-sql orm