0

I'm trying to add some info to the data result whether the user has read or write access to the entity.

Lets assume I have this entity:

public class Foo
{
   public int Id { get; set; }
   public string Name { get; set; }
   public virtual ICollection<Access> AccessRights { get; set; }
}

Where AccessRights holds the user id and if they have read/write access.

Currently I just $expand AccessRights and calculate if the user has read/write access in the frontend. However I'd like this calculated property to be added to the result.

Example json result:

{
   id: 1,
   name: "foo",
   hasReadAccess: true,
   hasWriteAccess: true
}

Is it possible to do this? Keep in mind that HasRead/WriteAccess doesn't exist on the model nor should it.

Snæbjørn
  • 10,322
  • 14
  • 65
  • 124

1 Answers1

0

You need to split your model in two: a data access model (what you get from the data access layer) and a data transfer model (what you send as a response).

Assuming your current Foo class as the data access model, you simply need to define another class FooResponse (or whatever name suits you) as follows.

public class FooResponse
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool HasReadAccess { get; set; }
    public bool HasWriteAccess { get; set; }
}

Then define a transformation function that maps from Foo instances to FooResponse instances. AutoMapper is a good tool for the job.

lencharest
  • 2,825
  • 2
  • 15
  • 22
  • That's how I usually do it. But I can't see how DTOs will play nice with OData controllers. – Snæbjørn Jan 04 '16 at 07:05
  • Why would it matter? The DTO is simply the entity type that the controller handles. – lencharest Jan 04 '16 at 17:30
  • Because the OData controller directly interacts with your repostory. That way you're able to filter and sort via the URL. – Snæbjørn Jan 05 '16 at 09:59
  • Hmm. I had assumed that you could add an `ODataQueryOptions` parameter to an action method that returns `IHttpActionResult` and then handle the query options inside the method using `ODataQueryOptions.ApplyTo`, but I see now that does not work. – lencharest Jan 06 '16 at 20:10