0

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

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

That's what I suspected. I solved it by implementing the logic in my repository. Really annoying "feature" by design... Thanks again.
@silkfire I believe you didn't understand the issue at all. It's by design, but it's how objects work not only in EF but in C# in general. You can't get properties already set before construction-time, and you can't set properties without initializers or constructors.........

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.