Home > Entity Framework > CodeFluent Entities vs Entity Framework: Computed property

CodeFluent Entities vs Entity Framework: Computed property


Computed properties are properties which are computed from other properties. For instance the full name is the concatenation of the first name and the last name. This value can be computed by the database or by the .NET code.

Let’s see how CodeFluent Entities and Entity Framework handle those properties.

Entity Framework

.NET

There is no magic, you have to add a partial class with a property FullName:

partial class Customer
{
    public string FullName
    {
        get { return string.Format("{0} {1}", this.FirstName, this.LastName); }
    }
}

This property is not part of the model so you cannot use it in T4 templates.

Database

Querying the database should be easy with EF, but in fact there are some subtleties. Here’s the Linq to Entities query:

var customers = from customer in context.Customer
                select new
                {
                    Id = customer.Id,
                    FullName = customer.FirstName + " " + customer.LastName
                };

If you look in details the result is not a list of Customer but a list of an anonymous type. In fact EF does not allows to instantiate a custom Entity object:

You can also define SQL function in the model, but you have to edit the Edmx file with an xml editor (without designer).

CodeFluent Entities

.NET

There are many possibilities:

1. As with Entity Framework we can add a new property in a partial class
2. We can also add a computed property directly to the model and code the OnGetFullName method in a partial class. This way we can benefit from the property when generating code from the model

private void OnGetFullName()
{
    this._fullName = string.Format("{0} {1}", this.FirstName, this.LastName);
}

3. When the computed property is a “string.Format” you can specify the format in the model so the code of the OnGetFullName method is automatically generated:

Database

The idea is to create a view which compute the full name.

Finally, you can load data from the SQL view using one line of code:

CustomerCollection.LoadCustomerWithFullName()

Conclusion

Both solutions allow to use computed properties. CodeFluent Entities provides some shorthand’s so you don’t always have to write code.

References:

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s