1
這是我的設置,在他們出現錯誤和描述之後。帶有接口和嵌套集合的AutoMapper EF
接口:
public interface IUser
{
int Id { get; set; }
string Firstname { get; set; }
string Lastname { get; set; }
string Email { get; set; }
string Fullname { get; }
}
public interface IPost
{
int Id { get; set; }
String Description { get; set; }
DateTime CreatedDate { get; set; }
int? UserId { get; set; }
IUser User { get; set; }
ICollection<IComment> Comments { get; set; }
}
public interface IComment
{
int Id { get; set; }
string Description { get; set; }
DateTime CreatedDate { get; set; }
int? PostId { get; set; }
int? UserId { get; set; }
IUser User { get; set; }
}
AutoMapper配置:
Mapper.Initialize(cfg => cfg.CreateMap<IUser, DAL.User>());
Mapper.Initialize(cfg => cfg.CreateMap<IComment, DAL.Comment>());
Mapper.Initialize(cfg => cfg.CreateMap<IPost, DAL.Post>()
.ForMember(d => d.User, m => m.MapFrom(s => s.User))
.ForMember(d => d.UserId, m => m.MapFrom(s => s.User.Id))
.ForMember(d => d.Comments, m => m.MapFrom(s => s.Comments))
);
Mapper.AssertConfigurationIsValid();
EF代碼:
public IEnumerable<IPost> GetPosts()
{
IQueryable<DAL.Post> query = dbSet.Posts.Include("Comments");
var result = Mapper.Map<IEnumerable<IPost>>(query);
return result;
}
錯誤:
{「上HiThere.DAL.User以下屬性不能映射:\ n \ TUSER \ n添加自定義映射表達式,忽略,添加自定義解析,或修改目標類型HiThere.DAL。 。用戶\ nContext:\ n \ tMapping從HiThere.Model.Common.IUser到類型的HiThere.DAL.User \ n異常 'AutoMapper.AutoMapperConfigurationException' 屬性用戶被拋出「}
描述:
我在ASP.NET WebAPI2項目中使用AutoMapper在DAL和模型之間映射數據。出於某種原因,我無法在使用嵌套對象時進行適當的映射。 任何幫助將不勝感激。
是不是所有的'cfg.CreateMap'都在一個'Mapper.Initialize'中?也沒有從'DAL'類到接口的映射。另外,如果'DAL'類實際實現了這些接口,爲什麼你需要AutoMapper? –
tkanks移動cfg.CreateMap o單Mapper.Initializer修復問題! –