A fairly simple extension I wanted to make to one of my imported entities was to provide a read-only, concatenated property. I tend to do this on any business object that represents a person to provide a single, read-only property for their full-name.
In a simple C# class, it would look like this:
To implement with the Entity Framework, the first thought might be to add this same property to the class produced… but of course this class is generated automatically by the framework, and hence any changes made would be overridden.
.Net’s concept of partial classes come to the rescue here. You simply make your own class with the same name as the class you wish to extend, declare it as partial and then implement your own property and/or method extensions:
In a simple C# class, it would look like this:
private string mstrFirstName;
private string mstrLastName;
public string FirstName
{
get { return mstrFirstName; }
set { mstrFirstName = value; }
}
public string LastName
{
get { return mstrLastName; }
set { mstrLastName = value; }
}
public string FullName
{
get { return mstrFirstName + ‘ ‘ + mstrLastName; }
}
To implement with the Entity Framework, the first thought might be to add this same property to the class produced… but of course this class is generated automatically by the framework, and hence any changes made would be overridden.
.Net’s concept of partial classes come to the rescue here. You simply make your own class with the same name as the class you wish to extend, declare it as partial and then implement your own property and/or method extensions:
namespace AssetManager.Models
{
public partial class User :
global::System.Data.Objects.DataClasses.EntityObject
{
public string FullName
{
get
{
return this.FirstName.Trim() + " " + this.LastName.Trim();
}
}
}
}
Comments
Post a Comment