Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; }
    }
like image 572
anu Avatar asked Oct 27 '15 21:10

anu


2 Answers

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.

like image 151
Bishoy Avatar answered Nov 18 '22 12:11

Bishoy


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;
        }
    }
}
like image 34
Praveen Paulose Avatar answered Nov 18 '22 12:11

Praveen Paulose