【问题标题】:Service Stack OrmLite and Identity_Insert服务堆栈 OrmLite 和 Identity_Insert
【发布时间】:2014-12-13 01:32:56
【问题描述】:

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

例如,在 SQL Server 中,当为表打开 Identity_Insert 时,标识值将完全按照指定插入,而不是自动生成。

【问题讨论】:

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


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

    例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多