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

asp.net-mvc c# entity-framework entity-framework-6

Question

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; }
    }
1
5
10/29/2015 12:33:54 AM

Accepted Answer

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.

18
10/28/2015 11:58:46 PM

Popular Answer

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;
        }
    }
}


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