Store read-only calculated field with Entity Framework Code First

柔情痞子 提交于 2019-11-29 06:21:04

Inspired by Slauma's answer, I was able to achieve what I was aiming for by using a protected setter. This persisted the value back to the database but didn't allow the value to be modified elsewhere.

My property now looks like this:

public int Duration
{
    get
    {
        return (int)this.EndTime.Subtract(this.StartTime).TotalMinutes;
    }
    protected set {}
}

Supplying an empty setter might be a possible solution (although then the property isn't readonly anymore, of course):

public int Duration
{
    get
    {
        return (int)this.EndTime.Subtract(this.StartTime).TotalMinutes;
    }
    set { }
}

As far as I know, readonly properties are not mappable to a column in the database.

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