Querying/Loading Model Relations

Back to Examples


If you don't know how to define model relationships, you should take a look at the [ForeignRelation] attribute, beforehand.

In order to make use of your model-defined relations, you need to specify the related model types at the time of retrieving data from the database using the Get(), ToIEnumerable(), or ToList() methods, or by using the LoadRelationships() method (NOTE: some overloads of this method require the specifying of the MagnaDB.<DbEngine> using reference since they're extension methods).

Specify foreign model types you wish to have loaded onto your models as arguments to the innerModelTypes parameter. This is done in order to prevent possible circular references, and resource overuse; always try to specify only the foreign relation model types you need to have loaded (Note that you can you can specify AS MANY AS YOU WISH and that this will load all specified foreign models recursively, not just the ones in the invoking class, but also the ones on foreign classes).

The use of the typeof operator is preferred.

using System;
using MagnaDB.SqlServer;

namespace TestMagnaDB
{
    class Program
    {
        static void Main(string[] args)
        {
            // Loading relationships with Get()
            Cat getCat = Cat.Get(1, typeof(Checkup));
            
            // Loading relationships with ToList()
            // ToIEnumerable works in the same fashion
            var toListKittens = Cat.ToList(new Type[] { typeof(Checkup) });

            // Loading relationships with LoadRelationships()
            // Note that the example class did not have a Owner property,
            // but it's implied (you can implement it by yourself) its
            // existence (being its type Person) for demonstrational purposes.
            getCat.LoadRelationships(typeof(Person);

            toListKittens.LoadRelationships(typeof(Person);
        }
    }
}