ORMLite Primary Key

Hello

I have my db POCO’s like this

[Schema("Core")]
[Alias("Matter_MatterType")]
public class MatterMatterType
{
    [PrimaryKey]
    [Required]
    public long MatterId { get; set; }

    [PrimaryKey]
    [Required]
    public int MatterTypeId { get; set; }

    [PrimaryKey]
    [Required]
    public int SystemId { get; set; }
}

Now while running the application and using it in my endpoints it works perfectly.

But when I have to write unit tests for it I have to drop the extra primary key attributes as @mythz you already mentioned

Multiple primary keys is not supported in OrmLite so you would not be able to create tables using OrmLite or use any of its APIs which rely on primary keys.

But to cater my needs of using those models in my testing architecture where I want to test few of my endpoints.
And I use in memory sqlite database how do I use them?

I did some search and found few ways

  1. Create table using raw query so we can add index on it to ensure the constraints
  2. Dont use primary key attribute instead use
[CompositeKey(nameof(MatterId), nameof(MatterTypeId), nameof(SystemId))]

Which way would you recommend? Because in my test setup I am creating connection like this

_container.Register<IDbConnectionFactory>(new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));


using (var db = _container.Resolve<IDbConnectionFactory>().Open())
{
    db.DropAndCreateTable<Core.MatterMatterType>();
}

One more way which I was using prev. was to create a Test mode where I would disable those primary key and enable them in my debug and prod

You’re not going to be able to use OrmLite to create tables with multiple primary keys since it doesn’t support multiple primary keys as its primary limitation. [CompositeKey] is not an OrmLite attribute it’s used by PocoDynamo to define Hash/Range Keys in DynamoDB Tables.

So you’d have to create the tables outside of OrmLite, e.g. by executing raw SQL CREATE TABLE statements which you can get OrmLite to generate with:

var sql = db.GetDialectProvider().ToCreateTableStatement(typeof(MatterMatterType))
    .Replace("PRIMARY KEY",""); // Modify generated SQL to suit...
db.Execute(sql);
1 Like

Okay thanks @mythz that was helpful for me