ASP.NET WebApi OData support for DTOs

前端 未结 3 1855
忘了有多久
忘了有多久 2020-12-15 08:34

I have Project entity and ProjectDTO. I\'m trying to create an WebAPI controller method that can take and return ProjectDTOs and make it support OData.

The problem i

3条回答
  •  情深已故
    2020-12-15 09:23

    Something like this (I haven't tried to compile it)

    using(var dataContext = new ORM_Context())
    {
        var projects = dataContext.Projects; // IQueryable
    
        //Create a set of ODataQueryOptions for the internal class
        ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
        modelBuilder.EntitySet("Project"); 
        var context = new ODataQueryContext(
             modelBuilder.GetEdmModel(), typeof(Project));
        var newOptions = new ODataQueryOptions(context, Request);
    
        var t = new ODataValidationSettings() { MaxTop = 25 };
        var s = new ODataQuerySettings() { PageSize = 25 };
        newOptions.Validate(t);
        IEnumerable internalResults =
            (IEnumerable)newOptions.ApplyTo(projects, s);
    
        int skip = newOptions.Skip == null ? 0 : newOptions.Skip.Value;
        int take = newOptions.Top == null ? 25 : newOptions.Top.Value;
    
        var projectDTOs =
                internalResults.Skip(skip).Take(take).Select(x =>
                    new ProjectDTO
                        {
                            Id = x.Id,
                            Name = x.Name
                        });
    
        var projectsQueriedList = projectDtos.ToList();
        var result = new ODataQueryResult(
            projectsQueriedList, totalCount);
        return result;
    }
    

提交回复
热议问题