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

放肆的年华 提交于 2019-12-05 11:56:04

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.

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

You could add a partial class QnsNew1 { public DayOfWeek Day { get; set; } } next to your generated data/model. But I would probably suggest that you separate your DataModel from your presentation model and this is a good reason why. Your presentation model will have parts to it that are just used for presentation and are computed on the fly whereas your data model should just strictly represent your data that is persisted.

Consider using a view model instead of model created by entity framework. I do not prefer using database models in my views because of the issue that you are facing. Instead I create a view model and then copy data from database model to view model using AutoMapper or some library like that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!