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?

2 Answers 2

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.

2
  • 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! Commented Oct 15, 2014 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: github.com/sjh37/…
    – Dai
    Commented Sep 2, 2021 at 5:54
17

You should add the [NotMapped] attribute to the property

1
  • 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
    Commented Sep 2, 2021 at 5:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.