Doubt regarding good practices with virtual properties

3

I have a project that contains my classes that represent my entities in my DB. So, as an example goes there:

In the Endereco table, I get a FK of Bairro(IdBairro) . To best represent my POCO , what is the best or only way? I do:

public virtual ICollection<Bairro> Bairros 

or simply

public virtual int IdBairro

Is there a time when I should use this or that approach?

    
asked by anonymous 01.07.2016 / 20:02

1 answer

3

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 ).

    
01.07.2016 / 20:26