Store read-only calculated field with Entity Framework Code First

后端 未结 2 839
梦毁少年i
梦毁少年i 2020-12-17 18:27

I am using Entity Framework Code First, and I have an entity defined with a StartTime property, an EndTime property and a Duration pro

相关标签:
2条回答
  • 2020-12-17 18:31

    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 {}
    }
    
    0 讨论(0)
  • 2020-12-17 18:33

    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 讨论(0)
提交回复
热议问题