我当时正在研究泛型,却陷入了奇怪的问题。我面临AutoMapper-9映射的问题。我已经实现了ICollection,但是Automapper无法正确映射属性。我的代码是
正在实现ICollection的CollectionBase类
public class CollectionBase<T> : ICollection<T>
{
ICollection<T> _items;
public CollectionBase()
{
_items = new List<T>();
}
protected CollectionBase(ICollection<T> collection)
{
// Let derived classes specify the exact type of ICollection<T> to wrap.
_items = collection;
}
public string FullName { get; set; }
public bool Enabled { get; set; }
public int Count
{
get
{
return _items.Count;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public void Add(T item)
{
_items.Add(item);
}
public void Clear()
{
_items.Clear();
}
public bool Contains(T item)
{
return _items.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_items.CopyTo(array, arrayIndex);
}
public IEnumerator<T> GetEnumerator()
{
return _items.GetEnumerator();
}
public bool Remove(T item)
{
return _items.Remove(item);
}
IEnumerator IEnumerable.GetEnumerator()
{
return _items.GetEnumerator();
}
}
ChildrenElements
public class ChildrenElements
{
public string SchoolName { get; set; }
public string CityName { get; set; }
}
ChildrenCollection->由CollectionBase继承
public class ChildrenCollection : CollectionBase<ChildrenElements>
{
public ChildrenCollection()
{
}
public int DefaultValue { get; set; }
}
儿童班
public class Children : IChildren
{
public Children()
{
}
public Children(IChildren children, bool flag = true)
{
Name = "Test";
FatherName = "TestFather";
childrenCollection = new ChildrenCollection() { DefaultValue = -1, FullName = "Children Name 1", Enabled = false };
if (children != null)
{
/////////////////////////////////////////////////////////////////////
//// Using Generic Mapper Configuration ///
/////////////////////////////////////////////////////////////////////
var mapper = ObjectMapperFactory.CreateMapper<IChildren, IChildren>();
mapper.Map(children, this);
}
}
public string Name { get; set; }
public string FatherName { get; set; }
public ChildrenCollection childrenCollection { get; set; }
}
AutoMapper的对象映射器工厂
public static class ObjectMapperFactory
{
public static IMapper CreateMapper<TSource, TDestination>()
{
var config = new MapperConfiguration(
cfg =>
{
cfg.CreateMap<TSource, TDestination>()
.PreserveReferences()
cfg.Advanced.AllowAdditiveTypeMapCreation = true;
cfg.AllowNullDestinationValues = true;
cfg.AllowNullCollections = true;
});
config.AssertConfigurationIsValid();
return config.CreateMapper();
}
}
映射器未映射“ ChildrenCollection”类内的属性。它正确映射了“ ChildrenElements”,但是ChildrenCollection类属性未正确映射,例如DefaultDays,Enabled等。
谢谢。