Sunday 15 May 2011

c# - How do I remove properties from related EF entities in Web API JSON response -



c# - How do I remove properties from related EF entities in Web API JSON response -

i'm working on web api 2 based service, using entity framework 6 persistence , asp.net identity authentication. utilize default identityuser implementation entity framework.

say have entity this:

public class illustration { [key] public string id { get; set; } public string foo { get; set; } public string bar { get; set; } public virtual identityuser owninguser { get; set; } }

and in web api controller, http request returns record way:

public async task<example> get( string id ) { var illustration = await _examplerepository.findbyidasync( id ); homecoming example; }

this works fine. however, request homecoming json such this:

{ id: "some id", foo: "some foo", bar: "some bar", owninguser: { claims: [], logins: [], roles: [ { userid: "some user id", roleid: "some role id" } ], securitystamp: "jadshgiuahsduigh", passwordhash: "adsghasdjgiasdg", email: "some@email.com", emailconfirmed: false, ... snip ... username: "some user", id: "some user id" } }

i don't want homecoming user data! i'd somehow intercept json that's beingness generated , whitelist properties include, in case, serialized identityuser object returned api include this:

owninguser: { username: "some user", id: "some user id" }

how can accomplish this? don't want truncate identityuser records across board; have can opt in on controller action basis. achieved action filter? , in pipeline interception need take place? ideally i'd want have custom serialization instances of identityuser in object graph i'm returning controller action, rather straight manipulating finished json response. i'm running web api owin middleware if that's relevant.

a solution using dtos, automapper/projection, setup dtos include want return, , using automapper , projection map original entities dtos, , vice versa.

using automapper : define userdto this:

public class userdto { public int id { get; set; } public string username { get; set; } }

then @ startup of app define mapping between identityuser , userdto this:

mapper.createmap<identityuser, userdto>();

and when have illustration entity, can map identityuser userdto this

var dto = mapper.map<userdto>(example.owninguser);

and homecoming dto.

using projection can utilize select linq method select field want homecoming database, this:

var userdto = dbexamplesset .select(e => e.owninguser) .select(u => new userdto { id = u.id, username = u.username }).singleordefault(u=> u.id == someuserid);

hope helps.

c# entity-framework asp.net-web-api asp.net-identity owin

No comments:

Post a Comment