Defining Data Models

Back to Examples


When defining MagnaDB Table/View Models there a few things to take into consideration.

Type Compatibility/Affinity

When working with MagnaDB, you can work with either Code-or-Database First Approaches on your application. Always make sure to check for type charts for the different types that are .NET compatible.

MagnaDB works with .NET CLR types, meaning that SQL specific custom types are not supported.

Key Definition

When defining your model always keep in mind that it needs to have a proper Key property defined in order to work. The Key doesn't necessarily have to be an Identity decorated property, it can also be composed of different properties of your model class.

The MagnaUtils.MakeKey() extension method is the easiest way to define your key, so use it to your advantage. We highly encourage you to.

Enums/Nullable types

If you wish to have properties that can handle null values, you do so by defining them with the Nullable<StructType> (adding a ? to a struct type does is a shorthand for this).

You can also use Enum types for your properties, and the mapped columns of the database will work using their underlying type (Enum types can also be marked Nullable).
Below an example of all these concepts applied.

using System;
using MagnaDB.SqlServer;

namespace TestMagnaDB
{
    public class Student : TableModel<Student>
    {
        protected override string ConnectionString => "Data Source=(local);Initial Catalog=testmagnadb;Integrated Security=True;";
        protected override string TableName => "Students";
        protected override MagnaKey Key => this.MakeKey(s => s.EnrollmentId);
        
        public string EnrollmentId { get; set; }

        [Identity]
        public int SystemId { get; set; }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime EnrollmentDate { get; set; }
        
        // This property can accept null values
        public DateTime? GraduatedOn { get; set; }

        // This is a quick example of enum properties
        public AcademicStatus Status { get; set; }

        // Let's say that null values represent that the student is not from a foreign country.
        public MigratoryStatus? MigratorySituation { get; set; }
    }

    // Since this enum's underlying type is byte, in SQL Server
    // it's matching type will be tinyint (this varies across DB engines)
    public enum AcademicStatus : byte
    {
        Enrolled,
        HasScholarship,
        Graduated,
    }

    // Enums' underlying type is int by default, so it's matching type
    // will be int for SQL Server (this varies across DB engines)
    public enum MigratoryStatus
    {
        Resident,
        Visa
    }
}