How to get Web API OData v4 to use DateTime

前端 未结 12 1210
时光取名叫无心
时光取名叫无心 2020-12-02 14:50

I have a fairly large data model that I want to expose using Web API OData using the OData V4 protocol.

The underlying data is stored in a SQL Server 2012 database.

12条回答
  •  失恋的感觉
    2020-12-02 15:16

    So far, DateTime is not the part of the OASIS OData V4 standard and Web API doesn't support the DateTime type while it do support the DateTimeOffset type.

    However, OData Team are working on supporting the DataTime type now. I'd expect you can use the DateTime type in the next Web API release. If you can't wait for the next release, I wrote an example based on the blog . Hope it can help you. Thanks.

    Model

    public class Customer
    {
        private DateTimeWrapper dtw;
    
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        public DateTime Birthday
        {
            get { return dtw; }
            set { dtw = value; }
        }
    
        [NotMapped]
        public DateTimeOffset BirthdayOffset
        {
            get { return dtw; }
            set { dtw = value; }
        }
    }
    
    public class DateTimeWrapper
    {
        public static implicit operator DateTimeOffset(DateTimeWrapper p)
        {
            return DateTime.SpecifyKind(p._dt, DateTimeKind.Utc);
        }
    
        public static implicit operator DateTimeWrapper(DateTimeOffset dto)
        {
            return new DateTimeWrapper(dto.DateTime);
        }
    
        public static implicit operator DateTime(DateTimeWrapper dtr)
        {
            return dtr._dt;
        }
    
        public static implicit operator DateTimeWrapper(DateTime dt)
        {
            return new DateTimeWrapper(dt);
        }
    
        protected DateTimeWrapper(DateTime dt)
        {
            _dt = dt;
        }
    
        private readonly DateTime _dt;
    }
    

    DB Context

    public DbSet Customers { get; set; }
    

    EdmModel

    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    
    builder.EntitySet("Customers");
    
    var cu = builder.StructuralTypes.First(t => t.ClrType == typeof(Customer));
    cu.AddProperty(typeof(Customer).GetProperty("BirthdayOffset"));
    var customer = builder.EntityType();
    
    customer.Ignore(t => t.Birthday);
    var model = builder.GetEdmModel();
    
    config.MapODataServiceRoute("odata", "odata", model);
    

    Controller

    Add the OData Controller as normal.

    Test

    Customer Data in the DB

    Payload

    The customers payload

提交回复
热议问题