带有OData的Web API 2中的只读属性 [英] Read only properties in Web API 2 with OData

查看:61
本文介绍了带有OData的Web API 2中的只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课

public class Person
{
    public DateTime DateCreated { get; set; }
    public string Name { get; set; }
}

我可以很高兴地使用OData对其进行配置:

I can happily configure it up with OData:

modelBuilder.Entity<Person>();

但是如何告诉OData我希望 DateCreated 是只读的?

But how can I tell OData that I want DateCreated to be read only?

推荐答案

如果DateCreated仅在服务器端有用,则可以通过添加属性来配置它不向客户端公开:

If DateCreated is only useful on the server side, then you can configure that it is not exposed to the client side by adding an attribute:

[System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute]
public DateTime DateCreated{get;set;}

在PeopleController中,您需要先设置其值,然后再将其存储到数据库或其他位置:

In the PeopleController, you need to set its value before store it to database or somewhere:

public class PeopleController
{
    public IHttpActionResult Post(Person person)
    {
        person.DateCreated=DateTime.Now;
        // Storing the person goes here
        return Created(person);
    }
}

现在不支持仅指示属性为ReadOnly.

Now it is not supported to just indicate that a property is ReadOnly.

这篇关于带有OData的Web API 2中的只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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