In my app I have to display some information about customers (a customer has a code and a name). One of the fields is ‘display name’, where
DisplayName = Code + " - " + Name
I retrieve the customer from database into a view model and set the DisplayName, like this:
from customer in this.Context.Customers
select new CustomerViewModel
{
DisplayName = customer.Code + " - " + customer.Name
}
But I would like to extract this logic into an expression or function because I use it in multiple places and if the logic changes (for example DisplayName = Name), then I have to do a lot of changes.
Therefore, I have created this function
Func<Customer, string> CustomerDisplayName = (c => c.Code + " - " + c.Name)
and use it this way:
from customer in this.Context.Customers
select new CustomerViewModel
{
DisplayName = CustomerDisplayName(customer)
}
It works fine and makes the logic reusable, but the problem is that the function cannot be parsed into an SQL statement, so LinqToSql first retrieves the data (‘Code’ and Name’) and then executes the function for each record.
Should I be worried about performance (if I have a lot of data), and stick with the first option ? Or is it ok to use the function ?
In your model you have the class Customer, which is a partial class (see the file yourDataClasses.designer.cs).
So, you only must to modify the file yourDataClases.cs, adding the partial class Customer and adding it the property DisplayName.
Your code in yourDataClases.cs looks like:
Your queries would be well: