从 C# 中的 WebApi OData (EF) 响应中排除属性 [英] Exclude property from WebApi OData (EF) response in c#

查看:28
本文介绍了从 C# 中的 WebApi OData (EF) 响应中排除属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C# 中的 WebApi 项目(首先使用 EF 代码)并且我正在使用 OData.我有一个包含 ID、姓名、姓氏、电子邮件和密码的用户"模型.

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

如果我调用/odata/Users,我将获得所有数据:ID、姓名、姓氏、电子邮件和密码.

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

如何从结果中排除密码但在控制器中保持可用以进行 Linq 查询?

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

推荐答案

我针对这个问题做了一个手工临时的解决方案(不是最好的解决方案,因为 UserInfo 不是实体类型,不支持 $select 或 $expand).我创建了一个名为 UserInfo 的新模型,其中包含我需要的属性(除了 User):

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

这篇关于从 C# 中的 WebApi OData (EF) 响应中排除属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆