22

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?

YodasMyDad
  • 9,248
  • 24
  • 76
  • 121

2 Answers2

23

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.

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
  • That's clever! In a way, it's sort of spooky because it seems *too* clever. Do we have any reason to believe that Microsoft might break this in a future EF release? I suppose I should worry too much as this answer is nearly four years old and it just worked for me! – Vivian River Oct 15 '14 at 17:25
  • @VivianRiver "Do we have any reason to believe that Microsoft might break this in a future EF release?" - `partial`-classes are a C# thing and have nothing to do with Entity Framework. Also, it's fundamental to how entity classes in EF work, including the latest versions of EF Core: though EF Core's scaffolding scripts and templates (for generating entity types from an existing database design) are rather _anemic_ so I always recommend using this instead: https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator – Dai Sep 02 '21 at 05:54
16

You should add the [NotMapped] attribute to the property

Jared Beach
  • 2,635
  • 34
  • 38
  • I'd like to add that the `[NotMapped]` attribute is only needed for properties with `get` and `set`. If you have a readonly property (e.g. a computed property with no `set`) then `[NotMapped]` is unnecessary. – Dai Sep 02 '21 at 05:52