Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service Stack OrmLite and Identity_Insert

When using Service Stack OrmLite how do you insert identity values exactly?

For instance in SQL Server when Identity_Insert is turned on for a table the identity value will be inserted exactly as specified and will not instead be auto generated.

like image 212
Telavian Avatar asked May 18 '26 15:05

Telavian


1 Answers

  1. Do not decorate your primary key with the [AutoIncrement] attribute. If you do so, then OrmLite will leave that column name and value out of the INSERT statement.
  2. Issue the SET IDENTITY_INSERT statement. Make sure to let OrmLite build 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"));
        }
    });
}
like image 74
sfuqua Avatar answered May 20 '26 16:05

sfuqua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!