Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding A Custom Property To Entity Framework?

Tags:

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 'CategoryName' 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?

like image 986
YodasMyDad Avatar asked Oct 19 '10 10:10

YodasMyDad


People also ask

How do I add custom properties to Entity Framework?

Right click the name of the entity on the designer and select Add, then Property from its context menu.

Does Efcore cache data?

The most common data to cache in EF Core is transactional data. This is the frequently changing data that is created at runtime (e.g. customer, accounts, activities, etc.) and you cache it only for a short time during which your application reads it multiple times.

How do I add entity framework to an existing project?

Install Entity FrameworkRight click on your project name and select Manage NuGet Packages. Go to Browse and Select Entity Framework then click Install button to install Entity Framework on your project.


1 Answers

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.

like image 102
Klaus Byskov Pedersen Avatar answered Oct 10 '22 16:10

Klaus Byskov Pedersen