OrmLite Service Stack and Identity_Insert

When using Service Stack OrmLite, how do you exactly insert credentials?

For example, in SQL Server, when Identity_Insert is enabled for a table, the identity value will be inserted exactly as specified and instead will not be automatically generated.

+3


source to share


1 answer


  • Do not decorate your primary key with the [AutoIncrement] attribute. If you do, OrmLite will keep that column name and value from the INSERT statement.
  • Run the SET IDENTITY_INSERT query. Make sure OrmLite creates the table name for you, taking into account any [Schema] and [Alias] attributes.

For example:



public void InsertAll(IEnumerable<TTable> set)
{
    const string identity = "SET IDENTITY_INSERT {0} {1}";
    var schema = typeof(TTable).FirstAttribute<SchemaAttribute>();
    var tableName = typeof(TTable).FirstAttribute<AliasAttribute>();
    var qualified = (schema == null ? "dbo" : schema.Name) + "." +
                    (tableName == null ? typeof(TTable).Name : tableName.Name);
    using (var db = _dbConnectionFactory.OpenDbConnection())
    {
        try
        {
            db.ExecuteSql(string.Format(identity, qualified, "ON"));
            db.InsertAll(set);
        }
        finally
        {
            db.ExecuteSql(string.Format(identity, qualified, "OFF"));
        }
    });
}

      

+1


source







All Articles