【发布时间】:2011-01-24 14:31:44
【问题描述】:
我正在使用ValueInjecter 将属性从域模型映射到通过服务层提供的 DTO。有问题的服务也接受更新...因此传入更新的 DTO,然后将其注入域对象并保存。
// Domain
public class Member
{
public Country Country { get; set; }
}
public class Country
{
public string Code { get; set; }
public string Name { get; set; }
}
//Dto
public class MemberDto
{
public string CountryCode { get; set; }
}
//Transformation Method attempt 1
public Member InjectFromDto (MemberDto dto, Member source)
{
source = source.InjectFrom<UnflatLoopValueInjection>(dto);
return source;
}
现在上面的代码所做的只是更新 Property Member.Country.Code 这显然不是我需要它做的。
所以从文档中,我想我需要创建一个覆盖并得到这个:
public class CountryLookup: UnflatLoopValueInjection<string, Country>
{
protected override Country SetValue(string sourcePropertyValue)
{
return countryService.LookupCode(sourcePropertyValue);
}
}
//revised transformation call
//Transformation Method attempt 2
public Member InjectFromDto (MemberDto dto, Member source)
{
source = source.InjectFrom<UnflatLoopValueInjection>(dto)
.InjectFrom<CountryLookup>(dto);
return source;
}
我的问题是在调试过程中,CountryLookup 永远不会被调用。
我能想到的可能原因:
- Nhibernate 代理类导致值注入器与 Country 类型不匹配?但这没有意义,因为它在展平期间起作用。
- 也许由于某种原因,unflattening 没有触发。即 Dto 是 CountryCode 而 Domain 是 Country.Code
我需要使用 Dto 上的 CountryCode 属性来调用 countryService.LookupCode 以返回要在更新注入期间使用的正确对象。
【问题讨论】:
-
告诉我们你想达到什么目标,第一次尝试成功,但不是你需要的,你需要什么?
-
您的名为 CountryLookup 的注入将从字符串转换为 Country,这意味着它看起来从字符串类型的 CountryCode 获取值并将其放入 Country.Code 类型的 Country
-
@Omu 是正确的,例如,如果我的 Country 对象是 Country: { Code: USA, Name: United States} 并且我的 Dto 传入 CountryCode: "CA" 它只是设置 Country.Code 属性到 CA 并将“名称”属性保留为美国。请记住,我正在更新一个预填充的域对象...因此,我需要调用我的 countryService 来查找正确的 Country 对象。我想从 Dto 中捕获“代码”,然后使用该代码查找正确的 Country 对象。
标签: nhibernate dto automapping valueinjecter