How to add new entity properties in Entity Framework without changing database model

19,123

Solution 1

A better approach

Although this can be easily done with Entity Framework, but as pointed out by other answers here, and I acknowledge 100%, that it is better to separate presentation/UI models from database models by creating ViewModel separate from your regular entities and put your calculated properties there.

If you are stuck with EF, keep reading

In EntityFramework Database First mode, the classes generated for the database model are partial classes. You can basically create another partial class with the same name and in the same assembly and namespace and add your calculated property there.

here is a complete example (after borrowing the day of week implementation from the answers here):

public partial class MyTable
{
    [NotMapped]
    public string DayOfWeek
    { 
        get 
        { 
            if (Date.HasValue)
                return DateTime.Now.DayOfWeek.ToString();
            else
                return null;
        } 
    }
}

It is important that you make sure the namespace is the same as the generated class. Also you will must annotate that property with NotMapped attribute so that EF does not attempt to map or save that property back to the database.

Solution 2

Create a partial class by the same name and have a getter property called Day. This will not add a column to your database.

public partial class QnsNew1
{
    public string Day
    {
        get
        {
            if (Date.HasValue)
                return DateTime.Now.DayOfWeek.ToString();
            else
                return null;
        }
    }
}
Share:
19,123
anu
Author by

anu

Updated on July 21, 2022

Comments

  • anu
    anu almost 2 years

    I am new to Entity Framework. I started with database first approach which created my classes corresponding to the tables I selected. I am using MVC. One of my tables has a Date column in it. My requirement is I want to display the Day in my gridview(Grid MVC) i.e. if Date for that particular record fetched is 10/27/2015, then Day should show Tues. I want to do this without adding an extra column for the day in my database. Is there a way for this. Any help will be greatly appreciated.

    My model class generated is as below:-

    public partial class QnsNew1
        {
            public int Id { get; set; }
            public Nullable<System.DateTime> Date { get; set; }
            public Nullable<int> PersonelID { get; set; }
            public string CType { get; set; }
            public string Comments { get; set; }
            //public string Day { get; set; }//I want to avoid doing this
            public virtual Personnel Personnel { get; set; }
            public virtual Type Type { get; set; }
        }
    
  • anu
    anu over 8 years
    Thanks!! [NotMapped] was an important thing that you pointed.