![](/img/trans.png)
[英]Converting a DTO's entityID to a Domain's entity through NHibernate and AutoMapper
[英]Automapper + DTO with an NHibernate Proxy
我在以下conf中使用AutoMapper將Nhibernate查詢中的對象轉換為我的DTO時遇到困難
假設我有4節課。
class A
{
//some fields of built-in type
}
abstract class B //Some class derived this one, but this is not important here
{
//some fields of built-in type
public A refA { get; set; }
}
class C
{
//some fields of built-in type
public B refB { get; set; }
}
class D
{
//some fields of built-in type
public B refC { get; set; }
}
我使用AutoMapper將其轉換為DTO,為簡單起見,這里假設DTO是這些類的精確副本。 我想通過電線發送它,因此在序列化之前,我要求AutoMapper將其轉換為D類對應的DTO。
如果我調用這些對象並自行配置字段,
Mapper.Map<T1,T2>(T1 source)
可以了 因此,我的配置AutoMap正在運行。 更多它也與
Mapper.Map<IList<T1>,List<T2>
很好。
現在,我將這些對象放入數據庫中,並使用Nhibernate調用對SQL DB的請求以檢索IList(類D的列表)。
如果我現在嘗試在DTO中對其進行轉換,它將不再起作用。 我在AutoMap中跟蹤代碼,它可以正確映射class D
所有內置類型字段,然后到達refC
並在此處崩潰。
我知道延遲加載和Nhibernate只是給我我對C類的引用的代理這一事實,但是我不知道如何解決這個問題。 如此您就知道NHibernateUtil.IsInitialized(refC) is true
非常感謝
您必須先取消代理您的實體,然后再將其傳遞給自動映射器。 這與運行Json序列化基本上是相同的問題。
您可以使用
Session.GetSessionImplementation().PersistenceContext.Unproxy();
取消代理。
或者您禁用延遲加載。
或者您不使用自動映射器,而是使用標准轉換...例如
.Query().Select(p => new SomeDto(){ PropA = p.PropA, ...});
您還可以使用另一種標准方式:
resultSet = session.CreateCriteria(typeof(DataObject))
.Add(query criteria, etc.)
.SetResultTransformer(Transformers.AliasToBean<DTOObject>())
.List<IDTOObject>()
基本上,您不必迭代所有道具。 DTO和數據對象之間的所有類道具都足夠相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.