Search code examples
odataasp.net-web-api2

Read only properties in Web API 2 with OData


I have a class:

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

I can happily configure it up with OData:

modelBuilder.Entity<Person>();

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


Solution

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

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

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