是否可以将ODataQueryOptions与DTO一起使用? [英] Is it possible to use ODataQueryOptions with DTO's?

查看:138
本文介绍了是否可以将ODataQueryOptions与DTO一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ContentType-> EF模型

ContentTypes-> DTO

在我的OData控制器中:

In my OData controller:

   public Task<IQueryable<ContentTypes>> Get(ODataQueryOptions<ContentTypes> options) 
   {
        var result = options.ApplyTo(_repository.Query().Get()
            .Where(u => u.UserId == userId)
            .OrderBy(o => o.Description))
            .Cast<ContentTypes>();

        return result;
   }

尝试应用ODataQueryOptions时出现错误500.由于该类已经继承了ODataController,我什至需要做options.ApplyTo(...)吗?

I get an error 500 when trying to apply the ODataQueryOptions. Since the class already inherits ODataController do I even need to do theoptions.ApplyTo(...)?

推荐答案

此解决方案是确保返回类型为DTO的类型,并且将ODataQueryOptions应用于EF实体.然后,我使用Automapper将结果映射到DTO.

The solution for this was to ensure the return type is the the DTO's type, and that the ODataQueryOptions are applied to the EF entity. I then use Automapper to map the result to the DTO.

我已经根据@Schandlich的建议更新了答案,但是仍然存在一些问题:

I have updated the answer based on @Schandlich 's suggestions, however some issues persist:

    [Queryable]
    public virtual IHttpActionResult Get(ODataQueryOptions<ContentType> options)
    {
        var userId = 102;   // mock

        try
        {
            var results = options.ApplyTo(_uow.Repository<ContentType>()
                .Query()
                .Get()
                .Include(u => u.User)
                .Where(u => u.UserId == userId)
                .OrderBy(o => o.Description)).Cast<ContentType>()
                .Select(x => new ContentTypeDTO()
                {
                    //projection goes here
                    ContentTypeId = x.ContentTypeId,
                    Description = x.Description,
                    UserDTO = new UserDTO 
                    { 
                        UserId = x.UserId,
                        UserName = x.User.UserName
                    }
                });

            return this.Ok(results);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

使用ODataQueryOptions的原因是我希望EF在数据库调用级别处理筛选.否则,我将返回所有记录,然后将Queryable插入以返回结果,例如结果的第一页.

The reason for using ODataQueryOptions is that I want EF to handle the filtering down at the database call level. Otherwise, I would get all records returned, then the Queryable would kick in to return, say the first page of results.

我删除了Automapper代码,但对为什么不使用它感到好奇?

I removed the Automapper code, but curious as to why not use this?

但是,如@Schandlich所指出的那样,这不适用于$select$expand.

As @Schandlich pointed out, however, this will not work for $select or $expand.

这篇关于是否可以将ODataQueryOptions与DTO一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆