使用OData在Web API 2中只读属性

时间:2014-07-17 12:38:03

标签: odata asp.net-web-api2

我有一个班级:

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

我很乐意用OData配置它:

modelBuilder.Entity<Person>();

但是我怎么能告诉OData我想要DateCreated只读?

1 个答案:

答案 0 :(得分:1)

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

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

在PeopleController中,您需要在将其存储到数据库或某处之前设置其值:

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

现在不支持仅表明属性是ReadOnly。