使用automap问题将ICollection映射到IEnumerable

时间:2013-07-15 20:03:01

标签: entity-framework automapper asp.net-web-api

遇到一个奇怪的问题,使用我的get方法工作,但在返回iqueryable时失败。使用投影或iqueryable时的一些限制? 我的代码如下所示,简化:

    public class SimpleEntity
    {
            public long Id { get; set; }
            public string Name { get; set; }
            public virtual SimpleEntity Parent { get; set; }
            public virtual ICollection<SimpleEntity> Children { get; set; }

            public SimpleEntity()
            {
                Children = new List<SimpleEntity>();
            }
    }

    public class SimpleEntityResponseDTO
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public NameValueItem ParentReferral { get; set; }
        public IEnumerable<NameValueItem> ChildReferrals { get; set; }

        public NavigationFolderResponseDTO()
        {
            ChildReferrals = new List<NameValueItem>();
        }
    }

    public class NameValueItem
    {
        public long Value { get; set; }
        public string Name { get; set; }
    }

网络API动作:

        [HttpGet, Queryable]
        public IQueryable<SimpleEntityResponseDTO> List()
        {
                //Generic crudservice returning an iqueryable based on Set<SimpleEntity>
                return _crudService.QueryableList().Project().To<SimpleEntityResponseDTO>();
        }

        [HttpGet]
        public HttpResponseMessage Get(long id)
        {
            SimpleEntity result = _crudSrv.Get(id);
            if (result != null)
                return Request.CreateResponse<SimpleEntityResponseDTO>(HttpStatusCode.OK, Mapper.Map<SimpleEntity , SimpleEntityResponseDTO>(result));
            else
                return Request.CreateResponse(HttpStatusCode.NotFound); 
        }

现在是映射:

Mapper.CreateMap<SimpleEntity, SimpleEntityResponseDTO>()
                .ForMember(to => to.ParentReferral, opt => opt.MapFrom(from => new NameValueItem { Name = from.Parent.Name, Value = from.Parent.Id }))
                .ForMember(to => to.ChildReferrals, opt => opt.MapFrom(from => from.Children.Select(o => new NameValueItem {Name = o.Name, Value = o.Id}).ToList() ));

无论如何,父映射都有效。但是儿童地图导致了以下问题。

当通过get方法检索对象时,一切都有效,无论我检索哪个实体。当使用List时,得到“对象引用未设置为对象的实例”,“d__b.MoveNext()\ r \ n ---从抛出异常的上一个位置的堆栈跟踪结束--- \ r \ n” 。试图例如添加$ filter = Id eq 5(或任何id)但导致相同的问题。也许有人可以暗示我这里出了什么问题?

0 个答案:

没有答案