简体   繁体   中英

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. 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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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