How to get ODATA to serialize NotMapped property

I have a WebAPI backend that provides inventory information, etc. to different clients using ODATA v3 (I cannot use v4 due to the limitation in the component we use). The inventory database is quite large (100K + records), and ODATA is great for server-side filtering, pagination, etc. And save data transfer.

There are some properties in inventory records that are not displayed, but rather are computed and populated on the fly when queries are executed. For instance:

[NotMapped] public decimal RebateAmount { get; set; } 

The problem is that ODATA ignores any NotMapped properties, so they are never sent back to clients.

I know that this was asked earlier, but it was a long time ago, so I was hoping that support for this was added by now or that someone has a simple workaround (if you do not allow EF to create these fields in the database).

I tried this ugly workaround but it didn't work (RebateAmount is still not included in ODATA):

 private decimal _rebateAmount; public decimal RebateAmount { get {return _rebateAmount; } } public void SetRebateAmount(decimal amount) { _rebateAmount = amount; } 

Is there a (preferably simple) way to include non-DB properties in ODATA result sets?

Edit 1/7/2017 For this to be useful in my scenario, ODATA must also include calculated fields in its metadata, otherwise automatically generated (client) proxy classes will not include them.

+7
source share
3 answers

I know this is an old post, but in the WebApiConfig file just add the following and it will open the "NotMapped" property.

 builder.StructuralTypes.First(t => t.ClrType == typeof(YourModel)).AddProperty(typeof(YourModel).GetProperty("RebateAmount")); 

Where the "builder" is your IEdmModel. Most likely in your GetEdmModel method.

+5
source

One approach may be to create an OData EDMModel with a DTO object with an additional computed property.

Please check this answer, which contains data about the execution: Matching an OData request with a DTO on another object?

A DTO can be mapped to a View at Database server or can be calculated in the controller using OdataQueryOptions .

+2
source

The easiest way (at least for EF Core): use fluent-api!

Instead of the NotMapped attribute, you can define it like this:

 modelBuilder.Entity<Product>().Ignore(p => p.RebateAmount); 

For EF6, you should also take a look at this question: EF Code First prevents properties from being displayed using the Fluent API

0
source

Source: https://habr.com/ru/post/1262383/


All Articles