سؤال

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.
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top