首先将实体框架代码存储只读计算字段 [英] Store read-only calculated field with Entity Framework Code First

查看:79
本文介绍了首先将实体框架代码存储只读计算字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架代码,我有一个实体定义了一个 StartTime 属性,一个 EndTime 属性和持续时间属性(以及其他一些)。 持续时间属性是一个计算字段,它是开始和结束时间之间的持续时间(以分钟为单位)。我的财产声明如下所示:

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

我想在代码中运行这个计算,但是持续时间持续时间持续到数据库以及开始和结束时间值(当我根据这些数字运行报告时,使之更容易在行中)。



我的问题是,如何获取这个只读属性,使用代码首先映射回保存到数据库?

解决方案

受到Slauma的回答的启发,我通过使用受保护的设定者来实现我的目标。这个值保留了数据库,但是不允许在其他地方修改该值。



我的资产现在如下所示:

  public int Duration 
{
get
{
return(int)this.EndTime.Subtract(this。开始时间).TotalMinutes;
}
protected set {}
}


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 and 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 {}
}

这篇关于首先将实体框架代码存储只读计算字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆