silkfire
silkfire

Reputation: 25935

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

Upvotes: 0

Views: 79

Answers (1)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64933

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

Upvotes: 1

Related Questions