Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a computed property in Data Services (OData)?

I am creating an OData service with WCF Data Services using an EDMX. How can I create a computed property for an entity type, so that its value gets computed in the service (C#) and does not come from the database?
The value of this property is based on the value of other properties, which are mapped to fields in the database.

like image 288
Fabrice Avatar asked Oct 05 '10 11:10

Fabrice


2 Answers

If you are exposing your EDMX file directly, using the default Entity Framework Provider for Data Services, something like this:

public class MyService: DataService<MyEntities> {

Then unfortunately you can't expose any 'new' properties that aren't in the underlying Entity Framework EDM model.

Having said that you have other options, you could write a reflection provider or custom provider that adds the extra property and delegates most of the work to EF under the hood.

The problem is setting up all the delegation is NOT easy today.

This series of posts explains providers and shows how to create a custom provider based service, and this one shows how to create a service using the Reflection Provider.

like image 143
Alex James Avatar answered Oct 24 '22 11:10

Alex James


The solution I found is to use Entity Framework Code First instead of an EDMX. It allows you to create computed properties just by creating standard properties in code.
Here is an example:

public class Person
{
  public String FirstName { get; set; }
  public String LastName { get; set; }
  public String FullName
  {
    get { return FirstName + " " + LastName; }
  }
}
like image 36
Fabrice Avatar answered Oct 24 '22 09:10

Fabrice