繁体   English   中英

如何使用Automapper映射集合

[英]How to map collections using Automapper

我有以下课程

 public class StateDto
    {
        public int Id { get; set; }
        public string StateName { get; set; }
        public string StateCode { get; set; }

    }
 public class CountryDto
    {

        public int Id { get; set; }
        public string CountryName { get; set; }
        public string CountryCode { get; set; }
        public List<StateDto> States { get; set; }
    }



public class Country : Entity, IValidatableObject
    {
        public Country()
        {
            States=new List<State>();
        }
        public string CountryName { get; set; }
        public string CountryCode { get; set; }
 // Few code related to IvalidatableObject removed
        public virtual ICollection<State> States { get; private set; }

        public void AddNewStatesInCountry(State state)
        {

            state.CountryId = Id;
            States.Add(state);

        }

       public bool IsDuplicateStateCodeExisits(string stateCode)
        {
            return States.Any(s => s.StateCode == stateCode);
        }

    }

public class State : Entity, IValidatableObject
    {
        public string StateName { get; set; }
        public string StateCode { get; set; }
        public int CountryId { get; set; }

      // Few code related to IvalidatableObject removed
    }

我正在使用以下代码映射这两个类

 Mapper.CreateMap<State, StateDto>();
    Mapper.CreateMap<Country, CountryDto>();  // Mapping Country to CountryDto

但是我在执行代码时遇到此错误

AutoMapper.AutoMapperMappingException : Missing type map configuration or unsupported mapping.

Mapping types:
Country -> CountryDto
Domain.ErpBase.CountryAgg.Country -> Application.ErpBase.Dto.CountryDto

Destination path:
CountryDto

Source value:
Domain.ErpBase.CountryAgg.Country

我的映射有什么问题,如何解决此问题。 类中的映射集合是否需要任何特殊的设置

NB:我尝试了countryMap.ForMember(cm => cm.States,mc => mc.MapFrom(co => co.States));

我认为您仅定义了从Country到CountryDto的映射。 您可能也需要相反的东西

Automapper处理集合,因此您的映射定义很好。

你应该,但是,提供一个公共的setter为StatesCountry

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM