Doubt regarding good practices with virtual properties

Asked

Viewed 62 times

4

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

On the table Endereco, I get a FK of Bairro(IdBairro). To play better in mine POCO, what is the best or only way? I do:

public virtual ICollection<Bairro> Bairros 

or simply

public virtual int IdBairro

There is a time when I must use this or that approach?

  • We are talking about Entity Framework?

  • @Gypsy omorrisonmendez yes, in this case yes.

1 answer

4


The modifier virtual serves to inform that this property can be modified by some class it inherits from this class, so it only makes sense for you to mark a property as virtual if you plan to create some class that you inherit from it and can modify the behavior of it.

Using as an example the Entity Framework, you could possibly have something like:

public class Endereco
{
    public int BairroID { get; set; }
    public virtual Bairro Bairro { get; set; }
}

This is because the Entity Framework need to create a runtime class. This class will override the property Bairro for her to perform a query when accessed, then we would have something like:

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 not even close to the implementation made by the Entity Framework, it is just there to illustrate the Lazy Loading carried out by the same.

Now, on the question, which is better, I advise you to follow the recommendation given by the ORM/Framework you are using.

In the case of Nhibernate, maybe it will be interesting to have all the properties virtual and not having the counter-party to the navigation properties, in this case you would have only the public virtual Bairro Bairro and would not have the public virtual int BairroID.

In Entity Framework, I would say to mark as virtual apenas the navigation properties, and maintain the navigation property and its counter-part, so you would have both public virtual Bairro Bairro, as public int BairroID (the latter without the virtual).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.