Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mattjcowan
Created March 29, 2020 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattjcowan/4c4997c00578e35815d7e9969a2bd861 to your computer and use it in GitHub Desktop.
Save mattjcowan/4c4997c00578e35815d7e9969a2bd861 to your computer and use it in GitHub Desktop.
Ormlite AddAttribute Issue
#!/usr/bin/env dotnet-script
#r "nuget: ServiceStack.OrmLite.Sqlite, 5.8.0"
#r "nuget: ServiceStack.Server, 5.8.0"
using ServiceStack;
using ServiceStack.Auth;
using ServiceStack.Configuration;
using ServiceStack.DataAnnotations;
using ServiceStack.OrmLite;
// to run this:
// $ dotnet tool install -g dotnet-script
// $ dotnet script ormlite-attr-issue.csx
// or if in `bash` terminal
// $ ./ormlite-attr-issue.csx
OrmLiteUtils.PrintSql();
var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);
// seems pretty innocent, but has a nasty side-effect that could be hard to track
// down when using dynamic plugin loading for example at startup
var x = typeof(ConfigSetting).GetModelMetadata();
// this call will work because the ModelDefinition has not yet been captured
typeof(ApiKey)
.GetProperty(nameof(ApiKey.Environment))
.AddAttributes(new StringLengthAttribute(53));
// this call will be IGNORED because the ModelDefinition has already been captured
typeof(ConfigSetting)
.GetProperty(nameof(ConfigSetting.Value))
.AddAttributes(new StringLengthAttribute(72));
// This approach always works, so is the recommended way
// ModelDefinition<ConfigSetting>.Definition
// .GetFieldDefinition(nameof(ConfigSetting.Value)).FieldLength = 73;
using(var db = dbFactory.OpenDbConnection())
{
db.CreateTable<ConfigSetting>();
db.CreateTable<ApiKey>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment