服务堆栈OrmLite和Identity_Insert

时间:2014-12-13 01:32:57

标签: sql-server sql-insert ormlite-servicestack

使用Service Stack OrmLite时,如何准确插入标识值?

例如,在SQL Server中为表启用Identity_Insert时,将严格按照指定插入标识值,而不会自动生成。

1 个答案:

答案 0 :(得分:1)

  1. 不要使用[AutoIncrement]属性装饰主键。如果这样做,那么OrmLite会将该列名和值保留在INSERT语句之外。
  2. 发出SET IDENTITY_INSERT语句。确保让OrmLite为您构建表名,同时考虑任何[Schema]和[Alias]属性。
  3. 例如:

    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"));
            }
        });
    }