Automapper返回空对象,源对象不为空.为什么会这样呢?
本文关键字:对象 为什么 返回 Automapper | 更新日期: 2023-09-27 17:50:27
所以我有这个webapiprice。web。api。models。category类
/*
* Service model class, that will represent categories
*/
using System;
using System.Collections.Generic;
namespace WebApiPrice.Web.Api.Models
{
public class Category
{
private List<Link> _links;
public long CategoryId { get; set; }
public string Name { get; set; }
public DateTime Timestamp { get; set; }
public List<Product> Products { get; set; }
public List<Link> Links
{
get { return _links ?? (_links = new List<Link>()); }
set { _links = value; }
}
public void AddLink(Link link)
{
Links.Add(link);
}
}
}
我试图映射到这个WebApiPrice.Data.Entities.Category类:
/*
* Domain class for database table Category
*/
using System;
using System.Collections.Generic;
namespace WebApiPrice.Data.Entities
{
public class Category : IVersionedEntity
{
private readonly IList<Product> _products = new List<Product>();
public virtual long CategoryId { get; set; }
public virtual string Name { get; set; }
public virtual User CreatedBy { get; set; }
public virtual User EditedBy { get; set; }
public virtual DateTime Timestamp { get; set; }
public virtual IList<Product> Products
{
get { return _products; }
}
public virtual byte[] Version { get; set; }
}
}
我的映射器配置是这样的:
using AutoMapper;
using WebApiPrice.Common.TypeMapping;
using WebApiPrice.Web.Api.Models;
namespace WebApiPrice.Web.Api.AutoMappingConfiguration
{
public class CategoryToCategoryEntityAutoMapperTypeConfigurator : IAutoMapperTypeConfigurator
{
public void Configure()
{
Mapper.CreateMap<Category, Data.Entities.Category>()
.ForMember(opt => opt.Version, x => x.Ignore())
.ForMember(opt => opt.CreatedBy, x => x.Ignore())
.ForMember(opt => opt.CategoryId, x => x.Ignore())
.ForMember(opt => opt.Name, x => x.Ignore())
.ForMember(opt => opt.EditedBy, x => x.Ignore())
.ForMember(opt => opt.Timestamp, x => x.Ignore());
}
}
}
我对映射器的调用在这里:
public Product AddProduct(NewProduct newProduct)
{
var productEntity = _autoMapper.Map<Data.Entities.Product>(newProduct);
productEntity.Category = _autoMapper.Map<Data.Entities.Category>(newProduct.Category);
productEntity.Type = _autoMapper.Map<Data.Entities.Type>(newProduct.Type);
_queryProcessor.AddProduct(productEntity);
var product = _autoMapper.Map<Product>(productEntity);
return product;
}
newProduct到Product可以映射,但是Category和type都不能。我的HTTP请求正文看起来像这样:
{"名称":"汤团"、"类别":{"被":"1","名字":"食物"},"类型":{"类型id":"1"}}
引用
我试着写有和没有名称的类别。newProduct。类别由给定的变量填充,数据库中有这样的值。
怎么了?还有什么需要我提供的信息吗?
我真的卡住了,任何建议都很有价值。尝试删除映射器中的忽略行:
public void Configure() {
Mapper.CreateMap<Category, Data.Entities.Category>();
}