sách gpt4 ăn đã đi

c# - 使用 AutoMapper 将 IList 映射到 (Iesi.Collections.Generic) ISet

In lại 作者:太空狗 更新时间:2023-10-29 18:29:57 24 4
mua khóa gpt4 giày nike

我已经尝试解决这个问题一天了,但一无所获,所以我希望有人可能已经解决了这个问题。我找到的最接近解决方案的是 How to simply map an NHibernate ISet to IList using AutoMapperMap IList to ICollection through AutoMapper但仍然没有快乐。

我有一个如下所示的数据对象:

public class Parent
{
public virtual ISet Children {get; set; }
}

还有一个如下所示的业务对象:

public class ParentDto
{
public IList Children {get; set; }
}

使用 AutoMapper 将数据映射到业务工作正常:

...
Mapper.CreateMap();
Mapper.CreateMap();
...

ParentDto destination = CWMapper.Map(source);

但是当我谈到从业务到数据的映射时,我得到了错误:

...
Mapper.CreateMap();
Mapper.CreateMap();
...

Parent destination = CWMapper.Map(source);

Unable to cast object of type 'System.Collections.Generic.List' to ''Iesi.Collections.Generic.ISet'

我添加了一个自定义映射:

Mapper.CreateMap()
.ForMember(m => m.Children, o => o.MapFrom(s => ToISet(s.Children)));

private static ISet ToISet(IEnumerable list)
{
Iesi.Collections.Generic.ISet set = null;

if (list != null)
{
set = new Iesi.Collections.Generic.HashedSet();

foreach (T item in list)
{
set.Add(item);
}
}

return set;
}

但我仍然得到同样的错误。任何帮助将不胜感激!

câu trả lời hay nhất

你可以使用AutoMapper的AfterMap()函数,像这样:

Mapper.CreateMap()
.ForMember(m => m.Children, o => o.Ignore()) // To avoid automapping attempt
.AfterMap((p,o) => { o.Children = ToISet(p.Children); });

AfterMap() 允许对 NHibernate 子集合处理的一些重要方面进行更细粒度的控制(例如替换现有集合内容而不是像这个简化示例中那样覆盖集合引用)。

关于c# - 使用 AutoMapper 将 IList 映射到 (Iesi.Collections.Generic) ISet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6722491/

24 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress