Search code examples
c#linqentity-frameworkdto

Hide some object fields before outputing?


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.

Solution

  • 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 });