我有以下代码:
我的课程(与此错误相关)
SizeEntity.cs
namespace DataObjects.EntityFramework
{
public class SizeEntity
{
public int Id { get; set; }
public string SizeName { get; set; }
}
}
Size.cs(在业务对象类库上)
namespace BusinessObjects
{
// Product business object
// ** Enterprise Design Pattern: Domain Model, Identity Field, Foreign key mapping
public class Size : BusinessObject
{
// ** Enterprise Design Pattern: Identity field pattern
public Size()
{
// establish business rules
AddRule(new ValidateRequired("SizeName"));
AddRule(new ValidateLength("SizeName", 1, 3));
}
public int Id { get; set; }
public string SizeName { get; set; }
}
}
SizeDao.cs
public class SizeDao : ISizeDao
{
/// <summary>
/// Constructor to initialize AutoMapper
/// </summary>
static SizeDao()
{
Mapper.Initialize(cfg => cfg.CreateMap<SizeEntity, Size>());
Mapper.Initialize(cfg => cfg.CreateMap<List<SizeEntity>, List<Size>>());
}
/// <summary>
/// Inserts size into database
/// </summary>
/// <param name="size"></param>
public void InsertSize(Size size)
{
using (var context = new ExamContext())
{
var entity = Mapper.Map<Size, SizeEntity>(size);
context.Sizes.Add(entity);
context.SaveChanges();
// update business object with new id
size.Id = entity.Id;
}
}
/// <summary>
/// Gets all size from database
/// </summary>
/// <returns>Returns a list of Sizes</returns>
public List<Size> GetSizes()
{
using (var context = new ExamContext())
{
var sizes = context.Sizes.ToList();
return Mapper.Map<List<SizeEntity>, List<Size>>(sizes);
}
}
}
我在此代码的最后一行收到映射错误。
返回Mapper.Map,List&gt;(sizes);
我在这里缺少什么?
错误消息在标题中: AutoMapperMappingException:缺少类型映射配置或不支持的映射,映射类型列表
更新1:
我删除了该行建议并仍然获得: 缺少类型映射配置或不支持的映射。
Mapping types:
SizeEntity -> Size
DataObjects.EntityFramework.SizeEntity -> BusinessObjects.Size
答案 0 :(得分:2)
首先,您应该删除指定对象List
的映射的初始化,您只需要定义与基础对象的映射。当您调用Map
方法时,初始化会导致结果为空。
static SizeDao()
{
Mapper.Initialize(cfg => cfg.CreateMap<SizeEntity, Size>());
// This is not needed.
// Mapper.Initialize(cfg => cfg.CreateMap<List<SizeEntity>, List<Size>>());
}
另外,正如@CodeCaster建议的那样,不要将映射定义放在静态构造函数中,例如,在整个应用程序的入口点,并验证在调用{{1}之前调用这些行方法。
答案 1 :(得分:0)
因为Automapper不起作用,所以我必须执行以下操作:
/// <summary>
/// Gets all size from database
/// </summary>
/// <returns>Returns a list of Sizes</returns>
public List<Size> GetSizes()
{
using (var context = new ExamContext())
{
var sizes = context.SizeEntities.ToList();
//Convert SizeEntities list to Size (Business Objects) list
var targetList = sizes
.Select(x => new Size() { Id = x.Id, SizeName = x.SizeName})
.ToList();
return targetList;
//return Mapper.Map<List<SizeEntity>, List<Size>>(sizes);
}
}