开发者

Store read-only calculated field with Entity Framework Code First

I am using Entity Framework Code First, and I have an entity defined with a StartTime property, an EndTime property and a Duration property (along with some others). The Duration property is a calculated field and it is the duration in minutes between the start an开发者_高级运维d end time. My property declarations are shown below:

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

I would like to run this calculation in code, but have the duration value persisted to the database along with the start and end time values (to make it easier later down the line when I come to run reports against these figures).

My question is, how can I get this read-only property to map back and save to the database using code first?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜