我正在使用 ValueInjecter将属性从域模型映射到通过服务层提供的 DTO。有问题的服务也接受更新......因此传入更新的 DTO,然后将其注入(inject)域对象并保存。
// 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 永远不会被调用。
我能想到的可能原因:
我需要使用 Dto 上的 CountryCode 属性来调用 countryService.LookupCode 以返回要在更新注入(inject)期间使用的正确对象。
最佳答案
unflattening 将是这样做:
entity.Country.Code <- dto.CountryCode
你需要的是:
entity.Country <- dto.CountryCode
因此,您的解决方案是继承一个 ExactValueInjection,您将从 CountryCode 转到 Country。
什么我建议你做和我在另一个项目的现场演示中做的一样http://awesome.codeplex.com
我有这样的东西:
public class Entity
{
public int Id{get;set;}
}
public class Member : Entity
{
public Country Country{get;set;}
}
public class MemberDto : DtoWithId
{
public int? Country {get;set;}
}
并使用这些注入(inject)从实体到 dto 并返回
public class NullIntToEntity : LoopValueInjection
{
protected override bool TypesMatch(Type sourceType, Type targetType)
{
return sourceType == typeof(int?) && targetType.IsSubclassOf(typeof(Entity));
}
protected override object SetValue(object sourcePropertyValue)
{
if (sourcePropertyValue == null) return null;
var id = ((int?) sourcePropertyValue).Value;
dynamic repo = IoC.Resolve(typeof(IRepo<>).MakeGenericType(TargetPropType));
return repo.Get(id);
}
}
//(you also need to have a generic repository, notice IRepo<>)
public class EntityToNullInt : LoopValueInjection
{
protected override bool TypesMatch(Type sourceType, Type targetType)
{
return sourceType.IsSubclassOf(typeof (Entity)) && targetType == typeof (int?);
}
protected override object SetValue(object o)
{
if (o == null) return null;
return (o as Entity).Id;
}
}
这些注入(inject)不仅可以处理来自 int 的处理吗?至国家 并返回,但也包括任何其他继承 的类型实体
关于nhibernate - 值注入(inject)器 : Dto to Domain Model (NHibernate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4783169/