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.
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<Image> Images { get; set; }
}
{
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);
[JsonIgnore]
but it's not an option since I will want to output Images
in some different request.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 });