Entity Framework 实体模型的值在 运行 构造函数时为空

Entity Framework entity model's values empty when running constructor

我正在我的项目中实现一个 POCO,它代表我数据库中的一行 table。我想修改构造函数中的一个值。

不幸的是,这些值似乎只在 之后 构造函数是 运行,所以没有办法我执行我需要的逻辑。这是错误还是设计使然?

我应该提一下我使用的是 Code First。

public partial class CheckpointValue
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [Column("saljare")]
        public int SalesAgentId { get; set; }

        [Column("volym")]
        public int Value { get; set; }

        [Column("datum")]
        public DateTime Date { get; set; }

        [Column("typ")]
        public string Type { get; set; }


        public CheckpointValue()
        {
            // Values empty... Why haven't they been populated when the constructor is run?
        }
    }

Unfortunately, it seems that the values are populated only after the constructor is run, so there's no way for me to perform my required logic. Is this a bug or by design?

这是设计使然。 顺便说一句,在不提供构造函数参数的情况下,您如何能够在构造时获取已经填充的这些属性?.

也许您试图在错误的地方实现您的逻辑。如果您正在寻找实施业务规则、域验证或谁知道什么,应该在另一个 class 中完成。例如,您的存储库是在返回请求的对象之前执行操作的好地方。

public CheckpointValue GetById(Guid id)
{
      CheckpointValue checkpointValue = YourDbContext.CheckpointValues.Find(id);
      // Implement here what you wanted in your class constructor...
      return checkpointValue;
}