2

Is it possible to hide certain fields before outputting it?

For the sake of simplicity let's say I have User and Image one user can have multiple images.

User

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Image> Images { get; set; }
}

Output

{
    Id: "1",
    Name: "Steve"
}

Now I want to output User with images and without. Is it possible to do something like this?
_db.Users.SingleOrDefault(x => x.Id == id).Except(x => x.Images);

  • This would be possible by adding [JsonIgnore] but it's not an option since I will want to output Images in some different request.
  • This would be possible by outputting anonymous objects but it's not an option.
  • This would be possible by creating DTO, but even so, how can I assign properties automatically from model to dto? Imagine that I have 30 fields, I don't want to assign them manually.
Stan
  • 25,744
  • 53
  • 164
  • 242

2 Answers2

0

Imagine that I have 30 fields, I don't want to assign them manually.

Automapper to the rescue!

PM> Install-Package AutoMapper

DTO:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Image> Images { get; set; }
}

public class UserInfo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Code:

Mapper.CreateMap<User, UserInfo>();

var user = new User { Id = 1, Name = "Bob" };

var userInfo = Mapper.Map<User, UserInfo>(user);

return Json(new { userInfo });
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
  • This isn't dynamic enough, image more complex system with 8 variables that may or may not be shown in result. – skmasq Aug 08 '13 at 21:46
  • This is only an example. Automapper has [a ton of features](https://github.com/AutoMapper/AutoMapper/wiki). – Dustin Kingen Aug 09 '13 at 00:04
0

I think this is also a solution which is worth your attention: You can define some base class or interface which contains elements you want, something like this:

public class UserBase {
  public int Id {get;set}
  public string Name {get;set;}
}
public class User : UserBase {
  public IEnumerable<Image> Images { get; set; }
}

//or using interface, I think this is better
public class IUserBase {
  int Id {get;set}
  string Name {get;set;}
}
public class User : IUserBase {
  public int Id { get; set; }
  public string Name { get; set; }
  public IEnumerable<Image> Images { get; set; }
}

Then in your LINQ query, you can do something like this:

var result = users.Select(x=>(IUserBase)x);
foreach(var user in result)
   System.Diagnostics.Debug.Print(user.Id + " : " + user.Name);//There is no `Images` element here except using explicitly cast to User type.
King King
  • 61,710
  • 16
  • 105
  • 130