Exemple #1
0
        /// <summary>插入</summary>
        /// <param name="session">实体会话</param>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public virtual Int32 Insert(IEntitySession session, IEntity entity)
        {
            var factory = Factory;

            // 添加数据前,处理Guid
            SetGuidField(factory.AutoSetGuidField, entity);

            IDataParameter[] dps = null;
            var sql = SQL(session, entity, DataObjectMethodType.Insert, ref dps);

            if (String.IsNullOrEmpty(sql))
            {
                return(0);
            }

            var rs = 0;

            //检查是否有标识列,标识列需要特殊处理
            var field  = factory.Table.Identity;
            var bAllow = factory.AllowInsertIdentity;

            if (field != null && field.IsIdentity && !bAllow && factory.AutoIdentity)
            {
                var id = session.InsertAndGetIdentity(sql, CommandType.Text, dps);
                if (id > 0)
                {
                    entity[field.Name] = id;
                }
                rs = id > 0 ? 1 : 0;
            }
            else
            {
                if (bAllow)
                {
                    var dal = DAL.Create(factory.ConnName);
                    if (dal.DbType == DatabaseType.SqlServer)
                    {
                        // 如果所有字段都不是自增,则取消对自增的处理
                        if (factory.Fields.All(f => !f.IsIdentity))
                        {
                            bAllow = false;
                        }
                        if (bAllow)
                        {
                            sql = $"SET IDENTITY_INSERT {session.FormatedTableName} ON;{sql};SET IDENTITY_INSERT {session.FormatedTableName} OFF";
                        }
                    }
                }
                rs = session.Execute(sql, CommandType.Text, dps);
            }

            // 清除脏数据,避免连续两次调用Save造成重复提交
            entity.Dirtys.Clear();

            return(rs);
        }