简体   繁体   English

运行构造函数时,实体框架实体模型的值为空

[英]Entity Framework entity model's values empty when running constructor

I'm implementing a POCO in my project that represents a row in my database table. 我在我的项目中实现了POCO,该POCO代表数据库表中的一行。 I'd like to modify one of the values in the constructor. 我想修改构造函数中的值之一。

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? 这是错误还是设计使然?

I should probably mention that I'm using Code First. 我可能应该提到我正在使用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? 这是错误还是设计使然?

This is by design. 这是设计使然。 BTW, how you would be able to get these properties already populated during construction-time without providing constructor arguments? 顺便说一句,在不提供构造函数参数的情况下,如何能够在构造期间填充这些属性? .

Maybe you're trying to implement your logic in the wrong place. 也许您试图在错误的地方实现逻辑。 If you're looking for implementing business rules, domain validation or who knows what, it should be done in another class. 如果您正在寻找实施业务规则,域验证或谁知道的知识,则应该在另一个类中完成。 For example, your repository would be a good place to do things before returning the requested object. 例如, 您的存储库将是返回请求的对象之前执行操作的好地方。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM