joshcomley
joshcomley

Reputation: 28818

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?

Upvotes: 0

Views: 1649

Answers (1)

Tan Jinfu
Tan Jinfu

Reputation: 3347

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.

Upvotes: 1

Related Questions