MC Fer
MC Fer

Reputation: 313

WebApi controller - How to hide some fields of a class in dbcontext result?

I have a class that has another class inside, but this class has some fields that i don´t want to show when call this controller. So, how can i hide ?

I tried to Include and do a Select with a new Class DTO, but not success. For example:

public class Father
{
 public string name {get;set}
 public FamilyName familyName {get;set;}
}
public class FamilyName
{
 public string name {get;set}
 public string sex {get;set}
}

Controller 

public IQueryable<Father> GetFathers()
{
 return db.Fater;
}

When i call the context Father, i have a Json with name and sex. If i need to just show the field "name", how should I do ?

Upvotes: 0

Views: 1685

Answers (2)

ElasticCode
ElasticCode

Reputation: 7867

You are Exposing database entities to the client, The client receives data that maps directly to your database tables, that's not always a good idea

You can define a data transfer object (DTO). A DTO is an object that defines how the data will be sent over the network.

DTO Class

public class FatherDTO
{
   public string name { get; set; }
}

Controller

public IQueryable<FatherDTO> GetFathers()
{
   return new FatherDTO(){ name = db.Fater.name };
}


You can convert to DTOs manually in code. Another option is to use a library like AutoMapper that handles the conversion automatically.

For more details check this link

Upvotes: 4

Amir Popovich
Amir Popovich

Reputation: 29836

There are a couple of ways to do so.

1.Create an anon. type with the wanted properties.

// controller
public object GetFathers()
{
    return db.Father.Select(f => new 
    { 
       name = f.name, 
       familyName = new { name = f.familyName.name }
    });
}

2.Create a DTO or the same class with a new instance using select. In order to do that, you will need the query to execute since EF cannot translate new Father into sql.

// controller
public IEnumerable<Father> GetFathers()
{
    return db.Father.ToList().Select(f => new Father
    { 
       name = f.name, 
       familyName = new FamilyName { name = f.familyName.name }
    });
}
  1. Do stuff with the JSON serializer (custom attributes\custom converters etc.)

Upvotes: 0

Related Questions