Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

mapping - How to simply map an NHibernate ISet to IList using AutoMapper

I'm trying to use AutoMapper to map from DTO's to my Domain.

My DTO's might look like this:

public class MyDTO
{
    public string Name { get; set; }
    public bool OtherProperty { get; set; }

    public ChildDTO[] Children { get; set;}
}

public class ChildDTO
{
    public string OtherName { get; set; }
}

My Domain objects like this:

public class MyDomain
{
    public string Name { get; set; }
    public bool OtherProperty { get; set; }
    public ISet<ChildDomain> Children { get; set; }
}

public class ChildDomain
{
    public string OtherName { get; set; }
}

How would I setup AutoMapper to be able to map from these Array's to Set's. It seems like AutoMapper is taking the Array's and converting them into IList's then failing on conversion to ISet.

Here's the exception

Unable to cast object of type 'System.Collections.Generic.List`1[DataTranser.ChildDTO]' to type 'Iesi.Collections.Generic.ISet`1[Domain.ChildDomain]'.

I'm hoping to find a simple generic way to do this so that I can minimize the infrastructure needed to map from DTO's to Domain. Any help is greatly appreciated.



UPDATE:
So then how would I model MyDomain -> ChildDomain without ending up with an anemic domain model? I understand that without business logic in MyDomain or ChildDomain the domain model is currently anemic, but the goal was to add business logic in as we move forward. I just want to ensure that my View Model can be translated into the domain model and persisted.

What would you suggest for this scenario, moving from a simple mapping between view and domain and later adding in business rules?

Thanks again for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If your persistence layer is simple, using UseDestinationValue() will tell AutoMapper to not replace the underlying collection:

ForMember(dest => dest.Children, opt => opt.UseDestinationValue())

However, if it's not simple, we just do the updating manually back into the domain. The logic generally gets more complex to update the domain model. Doing reverse mapping puts constraints on the shape of your domain model, which you might not want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...