Search code examples
c#linqentity-frameworkasp.net-web-apiodata

Exclude property from WebApi OData (EF) response in c#


I'm working with a WebApi project in C# (EF code first) and I'm using OData. I have a "User" model with Id, Name, LastName, Email, and Password.

In controller for example I have this code:

// GET: odata/Users
[EnableQuery]
public IQueryable<User> GetUsers()
{
    return db.Users;
}

If I call /odata/Users I'll get all the data: Id, Name, LastName, Email, and Password.

How can I exclude Password from results but keep available in controller to make Linq queries?


Solution

  • I made a craft and temporary solution to this problem (is not the best solution because UserInfo is not an entity type and not support $select or $expand). I created a new model called UserInfo just with the properties I need (apart of User):

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

    Then I changed the method in the controller:

    // GET: odata/Users
    [EnableQuery]
    public IQueryable<UserInfo> GetUsers()
    {
        List<UserInfo> lstUserInfo = new List<UserInfo>();
    
        foreach(User usr in db.Users)
        {
            UserInfo userInfo = new UserInfo();
            userInfo.Id = usr.Id;
            userInfo.Name = usr.Name;
            userInfo.Email = usr.Email;
    
            lstUserInfo.Add(userInfo);
        }
    
        return lstUserInfo.AsQueryable();
    }