Is it OK to have some logic codes inside a property of a data model class?

This calls for a method. Two reasons why:

  • I don't recommend setters for Collections
    • Property Usage Guidelines - Setting a property for each item in collection every time property is set is expensive and should not be in a property. A method is preferred instead.
  • Code (that you have in your case) in setter causes enough side-effects to disqualify use of property
    • Setters for collection type properties - A discussion on StackOverflow regarding setters for collections.

I suggest following:

public class QuizItem
{
    public int QuizItemId { get; set; }
    public string Question { get; set; }

    private IEnumerable<Choice> choices;
    public IEnumerable<Choice> Choices
    {
        get { return choices; }
    }

    public void SetChoices(IEnumerable<Choice> choices)
    {
        foreach (var x in choices)
            x.QuizItem = this;

        this.choices = choices;                
    }
}

Tags:

C#

Asp.Net Mvc