我正在利用Automapper和Entity Framework中的Project功能,但我遇到的问题是Automapper似乎不想将一个枚举类型投射到另一个.
我有以下实体:
public class UserProfile
{
public Guid Id { get; set; }
public string Name { get; set; }
private HashSet<UserProfilePhone> m_Phones;
public virtual HashSet<UserProfilePhone> Phones
{
get { return m_Phones ?? (m_Phones = new HashSet<UserProfilePhone>()); }
set { this.m_Phones = value; }
}
}
public class UserProfilePhone
{
public PhoneType Type { get; set; }
public virtual string Number { get; set; }
}
public enum PhoneType
{
Home = 1,
Work = 2,
Mobile = 3,
Other = 4
}
Run Code Online (Sandbox Code Playgroud)
然后,我将这些类型投影到以下模型:
public class UserProfileModel
{
public Guid Id { get; set; }
public virtual string Name { get; set; }
public IEnumerable<UserProfilePhoneModel> Phones { get; set; }
}
public class UserProfilePhoneModel
{
public UserProfilePhoneTypeModel Type { get; set; }
public string Number { get; set; }
}
public enum UserProfilePhoneTypeModel
{
Home = 1,
Work = 2,
Mobile = 3,
Other = 4
}
Run Code Online (Sandbox Code Playgroud)
然后我像这样设置我的映射:
Mapper.CreateMap<PhoneType, UserProfilePhoneTypeModel>();
Mapper.CreateMap<UserProfilePhone, UserProfilePhoneModel>();
Mapper.CreateMap<UserProfile, UserProfileModel>();
Run Code Online (Sandbox Code Playgroud)
最后我正在执行我的预测:
var result = dbContext.UserProfiles.Project().To<UserProfileModel>();
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我得到以下异常:
AutoMapper.AutoMapperMappingException:无法从MyNamespace.PhoneType到MyNamespace.Models.UserProfilePhoneTypeModel创建地图表达式无法从MyNamespace.PhoneType到MyNamespace.Models.UserProfilePhoneTypeModel创建地图表达式结果StackTrace:
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func
2 valueFactory) ...
我尝试过创建显式映射,但它们似乎被忽略了.我在这做错了什么?
RMD*_*RMD 14
像往常一样,我几乎在发布问题时就找到了答案.
修改创建地图行以提供显式强制转换可以解决问题:
Mapper.CreateMap<UserProfilePhone, UserProfilePhoneModel>()
.ForMember(m => m.Type, opt => opt.MapFrom(t => (UserProfilePhoneTypeModel)t.Type));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2790 次 |
最近记录: |