3
votes

I have a class used by Entity Framwork, called EFApplication.

Following this link, i want to add OData query option to my Web Api controller.

However, i don't want to use EFApplication class as the query parameters.

I want to use another class used just for the OData querying (ODataApplication)

Is this possible?

One of the reasons i want to use a different class is because OData doesn't support DateTime properties, and this means that i need to change it to DateTimeOffset, which i cannot do it (without breaking many other things)

// class mapped to Entity Frameowrk / Database
public class EFApplication
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual DateTime DateCreated { get; set; }
}

// class used for OData querying only
public class ODataApplication
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class ApplicationsController : ApiController
{
    [EnableQuery]
    public IQueryable<EFApplication> Get(ODataQueryOptions<ODataApplication> options)
    {
        // how to apply ODataQueryOptions<ODataApplication> query on top of EFApplication

        return result; // IEnumerable<EFApplication>
    }
}
2
One of possible solutions is to fill EdmModel manually based on EFApplication class but ignore DateTime field. Then you should be able to use it OData - Sergey Litvinov
Can you please give me an example of this? - Catalin

2 Answers

0
votes

You can fix this problem with Automapper and its feature Project().To()

// ViewModel class mapped to Entity Framework Model class
public sealed class EFApplicationViewModel
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public DateTimeOffset DateCreated { get; set; }
}

In your Controller for sample:

[EnableQuery]
    public IQueryable<EFApplication> Get(ODataQueryOptions<ODataApplication> options)
    {
        IQueryable<EFApplication> queryable = EFApplicationRepository.All();
        IQueryable<EFApplicationViewModel> projected = queryable.Project().To<EFApplicationViewModel>();

        return projected;
    }

In addition into Automapper you should set a little 'fix' for the DatetimeOffset(again sigh...)

Mapper.CreateMap<EFApplication, EFApplicationViewModel>();
Mapper.CreateMap<DateTime, DateTimeOffset>().ProjectUsing(src => src);
Mapper.CreateMap<DateTime, DateTimeOffset>().ConvertUsing(src => DateTime.SpecifyKind(src, DateTimeKind.Utc));
0
votes

If you block with DateTime, now it's not a problem.

Here's latest release of Web API OData 5.4 RC.

The release note is http://odata.github.io/WebApi/5.4-rc/

And here's a basic sample about the DateTime Support in Web API OData V4