Adding A Custom Property To Entity Framework?
I am using the Entity Framework for the first time and want to know if the following is possible - I have generated my classes from the DB, and have one called Category.
Obviously it has all my fields in the table (ID, CategoryName, SortOrder etc..) but I want to know if I can add a custom property which is not in the table, but is actually the result of a custom method.
I want to add a new property called 'CategoryURL' which is basically the 'CategoryNa开发者_运维问答me' property run through a custom method and returns a hyphenated string.
My initial thought is inheriting from the generated Category class and creating something like this inside?
public string CategoryURL
{
get{ return MyCustomMethod(this.CategoryName) }
}
Is this the correct approach? And will 'this.CategoryName' work as I think it should? Basically the end result is when I return a list of 'Category' I want this to be part of the class so I can use it in my foreach loop.
Hope this makes sense?
you should use a partial
class:
public partial class Category
{
public string CategoryURL
{
get{ return MyCustomMethod(this.CategoryName); }
}
}
This way this.CategoryName
will work just as expected.
This works because the classes generated by the entity framework code generator also generates partial
classes. It also means that you can safely re-generate the classes from the database without affecting the partial classes that you have defined yourself.
You should add the [NotMapped]
attribute to the property
精彩评论