Map a nullable entity
I am trying to map an id to object with AutoMapper and I have been trying to figure this out for two days. Any help would be appreciated.
Here are my domain objects:
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; }
}
Here is the edit model I'm using. Sales Person is a drop-down list of users with a "None" option (value=""
) as a customer may not have a sales person.
public class Cu开发者_如何学GostomerEditModel
{
[DisplayName("Sales Person")]
public Guid? SalesPerson { get; set; }
}
And here is where I am stuck. These are the mappings I have tried so far to map the edit model back to domain model:
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);
}
}
I made the following changes and things appear to be working as expected.
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));
精彩评论