我正在尝试使用AutoMapper将id映射到对象,我一直试图将其解决两天。任何帮助将不胜感激。
以下是我的域名对象:
public class Entity
{
public virtual Guid Id { get; protected set; }
}
public class Customer : Entity
{
public virtual User SalesPerson { get; set; }
}
public class User : Entity
{
public virtual string Email { get; set; }
}
这是我正在使用的编辑模型。销售人员是具有“无”选项(value=""
)的用户的下拉列表,因为客户可能没有销售人员。
public class CustomerEditModel
{
[DisplayName("Sales Person")]
public Guid? SalesPerson { get; set; }
}
这就是我被困的地方。这些是我到目前为止尝试将编辑模型映射回域模型的映射:
cfg.CreateMap<CustomerEditModel, Customer>()
.ForMember(d => d.SalesPerson, o => o.ResolveUsing<EntityResolver<User>>().FromMember(s => s.SalesPerson));
cfg.CreateMap<CustomerEditModel, Customer>()
.ForMember(d => d.SalesPerson, o => o.MapFrom(s => s.SalesPerson.HasValue ? s.SalesPerson.Value : null);
cfg.CreateMap<CustomerEditModel, Customer>()
.ForMember(d => d.SalesPerson, o => o.MapFrom(s => s.SalesPerson != null ? s.SalesPerson : null));
public class EntityResolver<T> : ValueResolver<Guid, T>
where T : Entity
{
protected override T ResolveCore(Guid source)
{
return session.Get<T>(source, LockMode.None);
}
}
答案 0 :(得分:0)
我做了以下更改,事情似乎按预期工作。
public class EntityResolver<id, entity> : ValueResolver<id, entity>
where entity : Entity
{
protected override entity ResolveCore(id source)
{
if (source != null)
return session.Get<entity>(source, LockMode.None);
else
return null;
}
}
...
cfg.CreateMap<CustomerEditModel, Customer>()
.ForMember(d => d.SalesPerson, o => o.ResolveUsing<EntityResolver<Guid?, User>>().FromMember(s => s.SalesPerson));