The modifier virtual
serves to inform that this property can be modified by some class that inherits from this class, so it only makes sense to mark a property as virtual
if you plan to create some class that inherits from it and can modify the behavior.
Using the Entity Framework as an example, you might have something like that:
public class Endereco
{
public int BairroID { get; set; }
public virtual Bairro Bairro { get; set; }
}
This occurs because Entity Framework
needs to create a class at runtime. This class will overwrite the Bairro
property so that it does a query when it is accessed, so we would have something like this:
public class Endereco_0C88CB7B3C2849FC85E80ECB5A1FAD4B : Endereco
{
private Bairro _bairro;
public override Bairro Bairro
{
get
{
if (bairro == null || bairro.BairroID != this.BairroID)
this._bairro = context.Bairros.Find(this.BairroID);
return this._bairro;
}
set
{
this._bairro = value;
this.BairroID = this._bairro!= default(Bairro) ? this._bairro.BairroID : default(int);
}
}
}
Note that the above implementation is neither close to the implementation made by the Entity Framework, it is just to illustrate the Lazy Loading .
Now, regarding the question, which is better, I advise you to follow the recommendation given by ORM / Framework you are using.
For NHibernate , it might be interesting to have all the virtual
properties and not have the counterpart for the navigation properties, in which case you would only have public virtual Bairro Bairro
and would not have to public virtual int BairroID
.
In the Entity Framework, I would say to mark as virtual apenas
the navigation properties, and keep the navigation property and its counterpart, then you would have both public virtual Bairro Bairro
and public int BairroID
(the latter without virtual
).