www.allpaul.com

I needed somewhere to put all this crap
Welcome to www.allpaul.com Sign in | Help
in Search

Programming

Adding computed properties to Entity Framework Entities

I have been working on a project using the Entity Framework.  One of the many cool features of the framework is it generates entity classes as partial classes so you, or in this case I, can extend an entity to include computed properties or methods.

In this example I have a Contact entity.  It has many properties including, FirstName, MiddleInitial and LastName.  I'd like to be able to access a property called FullName so I don't have to jump through all kinds of string null value checks and concatenation every time I need to display the contact's name. So, here is my entity Contact from the Entity Designer

Contact Entity

I can add to the partial class to include the property by creating a new class file (Contact.cs) and adding the correct namespace and including the partial keyword...Like this 

namespace DBModel 
{ 

    public partial class Contact 
    { 
        public string FullName 
        { 
            get 
            { 
                string ret = string.Empty; 
                if (!String.IsNullOrEmpty(FirstName)) 
                    ret += FirstName; 
                if (!String.IsNullOrEmpty(MiddleInitial)) 
                    ret += " " + MiddleInitial; 
                if (!String.IsNullOrEmpty(LastName)) 
                    ret += " " + LastName; 
                return ret; 
            } 
        } 
    } 

}

Now every time I need the contact's name I can just do a

     myContact.FullName

Sweet!

Only published comments... Jul 03 2008, 01:18 AM by paully21

Leave a Comment

(required) 
(optional)
(required) 
Submit

About paully21

 

Powered by Community Server (Non-Commercial Edition), by Telligent Systems