Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add methods to a model using entity framework

With entity framework, is it possible to add methods to an object class ? For example, i have a CLIENT mapping and i would like to create a "getAgeFromBirhDate" method.

like image 419
eka808 Avatar asked Nov 30 '10 14:11

eka808


People also ask

What is ModelBuilder in Entity Framework?

The ModelBuilder is the class which is responsible for building the Model. The ModelBuilder builds the initial model from the entity classes that have DbSet Property in the context class, that we derive from the DbContext class. It then uses the conventions to create primary keys, Foreign keys, relationships etc.


3 Answers

Yes. It's possible. Entity Framework generates Partial Classes.

That means you can create another file that contains another portion of the Partial Class definition (with your additional methods) and everything will work just fine.

like image 170
Justin Niessner Avatar answered Sep 22 '22 05:09

Justin Niessner


An example for the first answer:

if you have an entity named Flower you can use this partial class for adding method to it:

namespace Garden //same as namespace of your entity object
{
    public partial class Flower  
    {
        public static Flower Get(int id)
        { 
            //
        }
    }
}
like image 30
Majid Avatar answered Sep 21 '22 05:09

Majid


public static class ModelExtended
{
    public static void SaveModelToXML(this Model1Container model, string xmlfilePath)
    {
        ///some code
    }
}
like image 28
Sid C Avatar answered Sep 22 '22 05:09

Sid C