Search code examples
c#asp.net-mvcormlite-servicestack

Retrieving alias of a property from a Model with ORMLite and C#


I have the following class:

[Schema("dbo")]
[Alias("accesses")]
public class Acces{
    [Alias("id")]
    public int Id { get; set; }

    [Alias("device_id")]
    public string DeviceId { get; set; }

    [Alias("client_id")]
    public int ClientId { get; set; }

    [Alias("person_uid")]
    public string PersonUid { get; set; }

}

How can I programmatically retrieve, for example, the ORMLite Alias for PersonUid?

I tried using typeof(Access).GetModelMetadata() (dumping it too), but with no luck...


Solution

  • I made a helper for this on my project. Hope this helps!

    public static class OrmLiteExtensions
    {
        public static string GetQuotedName<T>(string propertyName, bool appendTablePrefix = true)
        {
            var sqlFieldName = string.Empty;
            var modelDefinition = typeof(T).GetModelMetadata();
            if (appendTablePrefix)
                sqlFieldName = OrmLiteConfig.DialectProvider.GetQuotedName(modelDefinition.ModelName) + ".";
            sqlFieldName += modelDefinition.FieldDefinitions.First(p => p.Name == propertyName).GetQuotedName(OrmLiteConfig.DialectProvider);
            return sqlFieldName;
        }
    }
    

    Usage:

    OrmLiteExtensions.GetQuotedName<Acces>(nameof(Acces.DeviceId), false); // pass true in second parameter to prefix with table name