Search code examples
sqliteunit-testingormlite-servicestackin-memory-database

ServiceStack SqLite Creation of Compute field


I am trying to use inMemory database (using ServiceStack.OrmLite.Sqlite.Windows) for unit testing in servicestack based web api. i created a table to insert into inmemory database using the existing Model class.The model class, table creation and insertion codes are as follows

            [Alias("Market")]
            public class Market
            {
                [AutoIncrement]
                [Alias("ID")]
                public int Id { get; set; }
                [Required]
                public int Available { get; set; }       
                [Required]
                public int AvailableSalesEvent { get; set; }
                [Compute]         
                [Required]
                public int AvailableTotal { get; set; }                  
                [Required]
                public int? MinCustomerBuy { get; set; }
            }


           db.DropAndCreateTable<Market>();
           var market = new Market()
            {                                       
                Available = 10,                                   
                AvailableTotal = 0,
                AvailableSalesEvent = 2,                                        
                MinCustomerBuy = 10
            };
            db.Insert(market); 

we are computing the AvailableTotal field value in our SqlServer while creating the Market table using the expression as follows,

        [AvailableTotal]  AS (isnull([Available]+[AvailableSalesEvent],(0)))

when i try to insert the above market object to the InMemory Database through unit test, i was getting following Exception

OneTimeSetUp: System.Data.SQLite.SQLiteException : constraint failed NOT NULL constraint failed: Market.AvailableTotal

i found out exception is a result of [Compute] attribute of Market Class, and got suggestions to replace it with [Compute, ServiceStack.DataAnnotations.Ignore], when i did the change InMemory Database tests are working fine but when i tested it through live database,even though the AvailableTotal value is computed and Updated in DB it is ignored and value 0 is assigned while returning response.

is there any way to define this AvailableTotal Field Expression while creating table in InMemory Database keeping the [Compute] attribute as it is to over come this Exception?


Solution

  • You can temporarily disable the computed behavior with:

    var fieldDef = typeof(Market).GetModelMetadata()
        .GetFieldDefinition<Market>(x => x.AvailableTotal);
    
    fieldDef.IsComputed = false;
    
    db.Insert(market);
    
    fieldDef.IsComputed = true;