vendredi 11 novembre 2016

Lazy load during save

I'm using lazy load for "relationship" properties and struggling when saving object because when I check to see if everything is OK before saving, the properties I'm checking get loaded from the db, losing the object's "saving" status. Consider this pseudo-code:

  public class Project 
  {
    private int _ProjectId;
    private string _ProjectName;
    private ProjectType _ProjectType;
    public int ProjectId
    {
      get { return _ProjectId; }
      set { _ProjectId = value; }
    }
    public string ProjectName
    {
      get { return _ProjectName; }
      set { _ProjectName = value; }
    }
    public ProjectType ProjectType
    {
      get
      {
        if (_ProjectId != 0 && _ProjectType == null)
        {
         ... load _Projectype from db here
        }
        return _ProjectType;
      }
      set
      {
        _ProjectType = value;
      }
    }
    public Project Save()
    {
      if(this.ProjectType != null) // <<-- if the _projectId is != 0 (typically during updates or delete operations, the prop is loaded from the db!!!
          adpt.Save(this);
    }
}

When the control is inside the class, I can of course reference the private member to avoid dynamic loading, but what if someone use the object from the outside? A simple test "if(Prj.ProjectType != null)" will inadvertently load the property.

It seems I need a state to inhibit the loading during saving operation and I was wondering if there is a pattern out there to help me.

Many thanks, Antonio

Aucun commentaire:

Enregistrer un commentaire