c# - Auto setting a data model property -


i trying set data model property value based on combination of 2 other property values within same instance of class. want work automatically when class instantiated. however, if use constructor this, none of other model properties have been set @ point.

then, whenever try access property, null returned. guidance on how approach scenario grateful.

model:

i trying set versionschemecode have value of combination of both version , scheme.schemecode. however, nothing saved database.

public class schemeversion {     private string _versionschemecode;      [key]     [databasegeneratedattribute(databasegeneratedoption.identity)]     public int id { get; set; }      [required]     public int version { get; set; }      [required]     public int schemeid { get; set; }      [foreignkey("schemeid")]     public virtual scheme scheme { get; set; }      public string versionschemecode     {                 {             return _versionschemecode;         }         set         {             using(var db = new mydbcontext())             {                 var schemecode = db.schemes.singleordefault(x => x.schemeid == this.schemeid).schemecode;                  _versionschemecode = string.format("{0}_v{1}", schemecode, this.version.tostring());             }         }     }           } 

just couple of points:

if versionschemecode calculated (as opposed persisted) leave out getter , have setter build string based on other property values.

alternatively, use regular properties (with private backing fields) version , scheme , update versionschemecode value time set. following... (however, need aware time version or scheme properties changes versionschemecode updated reflect this.)

private int _version;  [required] public int version  {         {        return _version;     }    set;     {        _version = value;        versionschemecode = string.format("{0}{1}", version, scheme.schemecode);    } } 

finally, don't particularly including data access code in poco's. pocos should ideally database , orm agnostic. prefer have kind of dataaccessservice getschemeversion call. retrieve , hydrate entity , call function populate calculated properties before returning it.

public schemeversion getschemeversion(int id) {         using(var db = new mydbcontext())         {             var entity = db.schemesversions.singleordefault(x => x.id == id);             entity.setcalculatedvalues();             return entity;         }          } 

Comments