3

Is it possible to define dynamic schema with OrmLite in runtime. For instance, when reading object through OrmLite is it possible to define which schema to read it from.

This would be best shown through an example. Let's say I have 3 User tables inside MSSQL 2008 R2 database:

Schema1.user Schema2.User Schema3.User

I have an object User with some properties defined. I select data like this "db.Select();". The problem is I have not defined from which schema to read User data from. I want to be able to do this at runtime, but I can't seem to find a propert way to do it.

Using C#, .NET 4.5 fw, MSSQL 2008 R2 Database

Thank you!

DeBigBos
  • 31
  • 2

2 Answers2

1

You can do this by modifying OrmLite's metadata that it maintains for each type, i.e:

var modelDef = SqlServerOrmLiteDialectProvider.GetModelDefinition(typeof(Poco));
var existingSchema = modelDef.Schema;
modelDef.Schema = "Schema2";

// All queries on Poco now use `Schema2`

modelDef.Schema = existingSchema; //Retain existing behavior
mythz
  • 141,670
  • 29
  • 246
  • 390
  • What if this must be used with multithreading? For example, one user must use Schema1, other user must user Schema2. The best way (as I see it) would be, if you could specify schema when calling extension methods (e.g. Select). – DeBigBos Jun 19 '14 at 07:03
  • 1
    @DeBigBos It's mutating a singleton instance so it does affect other threads. Creating overloads is not a winning strategy as it disrupts and complicates the API surface for each option introduced. It's better to use scoped configuration for overriding default config. – mythz Jun 19 '14 at 07:15
-1

This functionality has gotten easier in the current release. You can just do data annotations over the class to set the as is explained here.

example:

[Schema("test")]
public class Foo 
{
}
Dan Csharpster
  • 2,662
  • 1
  • 26
  • 50
  • OP was asking for a way to set a dynamic schema at runtime. Your solution works only for a single schema that is known at compile time. Or it would require to create n duplicates of the class with different Schema annotations. – Tarnschaf Apr 20 '20 at 12:46