Entity Framework: How Do I Add A Custom Property?

asp.net c# entity-framework linq

Question

I have produced my classes from the database and have one named Category. I am using the Entity Framework for the first time and want to know whether the following is doable.

All of my fields—ID, CategoryName, SortOrder, etc.—are obviously present in the table, but I'm wondering whether I can also add a custom property that isn't part of the table but rather the output of a custom function.

In essence, the "CategoryName" field is the "CategoryURL" property passed via a custom method, which produces a hyphenated string.

My first notion was to create something similar within the automatically produced Category class by inheriting from it.

public string CategoryURL 
{
    get{ return MyCustomMethod(this.CategoryName) }
}

Is this the best course of action? Will "this.CategoryName" function as I believe it should? In short, I want the list of "Category" items I return to be a part of the class so I can utilize it in my foreach loop.

I hope I made sense.

1
20
10/19/2010 10:36:58 AM

Accepted Answer

Use a partial class, please:

public partial class Category
{
    public string CategoryURL  
    { 
        get{ return MyCustomMethod(this.CategoryName); } 
    } 
}

So as tothis.CategoryName will perform as anticipated.

This works because the entity framework code generator also creates classes.partial courses. Additionally, it implies that the partial classes you have specified yourself won't be impacted when you securely regenerate the classes from the database.

21
1/21/2014 2:48:23 PM

Popular Answer

You must include the[NotMapped] a component of the property



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow