我有几十个域对象(用户,组,角色,社区,帖子等).此外,我有扩展的对象(UserExt,GroupExt等),这些对象派生自那些并包含一些附加数据.在我的数据访问控制层中,有一些检索基础对象的方法.当我需要使用数据填充子对象时,我使用这些方法,但每次我需要将该结果转换为子类型.
因为我不能将父对象转换为子对象,所以我需要为每个父子对提供转换器(通过构造函数,方法,现有转换器的扩展或任何其他方式).这就是我不喜欢的,好像我曾经添加任何字段到基本类型我可能忘记调整我的转换器.是否有更多自动化方式从父母那里填充孩子的字段?
谢谢!
PS:代码:
域对象:
public class Role : OutdoorObject
{
public String Name { get; set; }
public Int32 CreatedById { get; set; }
public Int32 UpdatedById { get; set; }
}
public class RoleExt : Role
{
public IPrincipal CreatedBy { get; set; }
public IPrincipal UpdatedBy { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
数据访问层:
public Role GetById(Int32 roleId)
{
try
{
// seek in cache, return if found
LQ_Role lqRole = context.LQ_Roles.FirstOrDefault(r => r.RoleID == roleId);
Role result = LQMapper.LQToObject(lqRole);
// put result to cache
return result;
}
catch (Exception ex)
{
if (ex is BaseRepositoryException) throw ex;
else throw new UnknownRepositoryException(ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
服务层:
public Role GetById(IPrincipal Executer, int roleID)
{
try
{
// perform operation
Role r = _repo.GetById(roleID);
// check access
if (!CanRead(Executer, r)) throw new OperationIsNotPermittedServiceException();
return r;
}
catch (Exception ex)
{
// ...
}
}
public RoleExt GetExtById(IPrincipal Executer, int roleID)
{
try
{
// perform operation
Role r = GetById(IPrincipal Executer, int roleID);
RoleExt result = new RoleExt();
// here i need to convert r to result
// and populate addition fields
result.CreatedBy = userService.GetById(Executer, r.CreatedById);
result.UpdatedBy = userService.GetById(Executer, r.UpdatedById);
// check access
if (!CanRead(Executer, result)) throw new OperationIsNotPermittedServiceException();
return result;
}
catch (Exception ex)
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
使用反射,这会将所有公共属性从父级复制到子级:
public static void CopyOver(Parent p, Child c)
{
PropertyInfo[] props = p.GetType().GetProperties(BindingFlags.Public);
foreach( PropertyInfo pi in props)
{
pi.SetValue( c, pi.GetValue( p) );
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2375 次 |
| 最近记录: |