0

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 ?

2
  • In the GetFathers() method, you need to fetch all the Father objects from the database and explicitly map them to the Father DTO object. Commented Apr 6, 2018 at 20:05
  • Create another DTO class with fields you want to show in controller and map its values from entity class Commented Apr 6, 2018 at 20:16

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.