示例#1
0
        public void DropTable(Domain.Entity entity)
        {
            Sql dropSql = Sql.Builder.Append(string.Format("IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[{0}]')) ", entity.Name))
                          .Append(string.Format("DROP TABLE [dbo].[{0}]", entity.Name));

            _database.Execute(dropSql);
        }
示例#2
0
        public void DropView(Domain.Entity entity)
        {
            Sql dropSql = Sql.Builder.Append(string.Format("IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[{0}View]') AND OBJECTPROPERTY(id, N'IsView') = 1) ", entity.Name))
                          .Append(string.Format("DROP VIEW [dbo].[{0}View]", entity.Name));

            _database.Execute(dropSql);
        }
示例#3
0
        public bool CreateWorkFlowAttributes(Domain.Entity entity)
        {
            var existAttributes = _attributeRepository.Query(f => f.EntityId == entity.EntityId && f.Name.In("WorkFlowId", "ProcessState"));

            if (existAttributes != null && existAttributes.Count() == 2)
            {
                return(true);
            }
            var workFlowPrimaryKey             = entity.WorkFlowEnabled ? _attributeRepository.Find(x => x.EntityName == "WorkFlow" && x.Name == "WorkFlowId") : null;
            List <Domain.Attribute> attributes = new List <Domain.Attribute>();

            if (!existAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("WorkFlowId")))
            {
                attributes.Add(new Domain.Attribute()
                {
                    AttributeId = Guid.NewGuid(), EntityId = entity.EntityId, Name = "WorkFlowId", LocalizedName = _loc["entity_sys_workflowid"], AttributeTypeName = AttributeTypeIds.LOOKUP, EntityName = entity.Name, ReferencedEntityId = workFlowPrimaryKey.EntityId, IsNullable = true, IsRequired = false, LogEnabled = false, IsCustomizable = false, IsCustomField = false
                });
            }

            if (!existAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("ProcessState")))
            {
                attributes.Add(new Domain.Attribute()
                {
                    AttributeId = Guid.NewGuid(), EntityId = entity.EntityId, Name = "ProcessState", LocalizedName = _loc["entity_sys_processstate"], AttributeTypeName = AttributeTypeIds.PICKLIST, EntityName = entity.Name, OptionSetId = Guid.Parse("00000000-0000-0000-0000-000000000001"), IsNullable = true, IsRequired = false, LogEnabled = false, IsCustomizable = false, IsCustomField = false, DefaultValue = "-1"
                });
            }
            foreach (var attr in attributes)
            {
                Create(attr);
            }
            return(true);
        }
示例#4
0
        public void AlterView(Domain.Entity entity, List <Domain.Attribute> attributes, List <Domain.RelationShip> relationShips)
        {
            Sql dropSql = Sql.Builder.Append(string.Format("IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[{0}View]') AND OBJECTPROPERTY(id, N'IsView') = 1) ", entity.Name))
                          .Append(string.Format("DROP VIEW [dbo].[{0}View]", entity.Name));
            Sql createSql = Sql.Builder.Append(string.Format("CREATE VIEW [{0}View] AS", entity.Name))
                            .Append("SELECT");//.Append("GO");

            List <string> attrNames = new List <string>();

            foreach (var item in attributes)
            {
                attrNames.Add(string.Format("[{0}].[{1}]", entity.Name, item.Name));
            }

            foreach (var item in relationShips)
            {
                if (attributes.Exists(n => n.AttributeId == item.ReferencingAttributeId))
                {
                    attrNames.Add(string.Format("[{0}].[Name] AS {1}Name", item.Name, item.ReferencingAttributeName));
                }
            }

            createSql.Append(string.Join(",\n", attrNames));
            //tables
            createSql.Append(string.Format("FROM [{0}] WITH(NOLOCK)", entity.Name));
            foreach (var item in relationShips)
            {
                createSql.Append(string.Format("LEFT JOIN [{1}] AS [{3}] WITH(NOLOCK) ON [{2}].[{0}]=[{3}].[{4}]", item.ReferencingAttributeName, item.ReferencedEntityName, entity.Name, item.Name, item.ReferencedAttributeName));
            }
            _database.Execute(dropSql);
            _database.Execute(createSql);
        }
示例#5
0
        public bool Create(Domain.Entity entity, params string[] defaultAttributeNames)
        {
            if (_entityRepository.Exists(x => x.Name == entity.Name))
            {
                throw new XmsException(_loc["name_already_exists"]);
            }
            var solutionid = entity.SolutionId;                     //当前解决方案

            entity.SolutionId = SolutionDefaults.DefaultSolutionId; //组件属于默认解决方案
            var result = true;

            if (defaultAttributeNames.IsEmpty())
            {
                //默认添加主键字段
                defaultAttributeNames = new string[] { entity.Name + "Id" };
            }
            else if (!defaultAttributeNames.Contains(entity.Name + "Id", StringComparer.InvariantCultureIgnoreCase))
            {
                var namesList = defaultAttributeNames.ToList();
                namesList.Add(entity.Name + "Id");
                defaultAttributeNames = namesList.ToArray();
            }
            var parentEntity      = entity.ParentEntityId.HasValue ? _entityRepository.FindById(entity.ParentEntityId.Value) : null;
            var defaultAttributes = _defaultAttributeProvider.GetSysAttributes(entity).Where(x => defaultAttributeNames.Contains(x.Name, StringComparer.InvariantCultureIgnoreCase)).Distinct().ToList();

            using (UnitOfWork.Build(_entityRepository.DbContext))
            {
                result = _entityRepository.Create(entity, defaultAttributes, _defaultAttributeProvider.GetSysAttributeRelationShips(entity, defaultAttributes));

                //创建默认字段
                _attributeCreater.CreateDefaultAttributes(entity, defaultAttributeNames);
                //如果是子实体,则创建引用字段
                if (parentEntity != null)
                {
                    _attributeCreater.Create(new Domain.Attribute {
                        Name = parentEntity.Name + "Id"
                        , AttributeTypeName  = AttributeTypeIds.LOOKUP
                        , EntityId           = entity.EntityId
                        , EntityName         = entity.Name
                        , IsRequired         = true
                        , LocalizedName      = parentEntity.LocalizedName
                        , ReferencedEntityId = parentEntity.EntityId
                    });
                }
                //事件发布
                _eventPublisher.Publish(new ObjectCreatedEvent <Domain.Entity>(entity));
                //solution component
                _solutionComponentService.Create(solutionid, entity.EntityId, EntityDefaults.ModuleName);
                //本地化标签
                _localizedLabelService.Append(entity.SolutionId, entity.LocalizedName.IfEmpty(""), EntityDefaults.ModuleName, "LocalizedName", entity.EntityId)
                .Append(entity.SolutionId, entity.Description.IfEmpty(""), EntityDefaults.ModuleName, "Description", entity.EntityId)
                .Save();

                //add to cache
                _cacheService.SetEntity(entity);
            }
            return(result);
        }
 public bool SaveMyEntity(Domain.Entity myEntity)
 {
     using (var context = _contextGenerator.GenerateMyDbContext())
     {
         var entityToUpdate = context.Entities.FirstOrDefault();
         if (entityToUpdate == null)
         {
             entityToUpdate = new Domain.Entity();
             context.Entities.Add(entityToUpdate);
         }
         PropertiesHelper.CopyProperties(myEntity, entityToUpdate);
         context.SaveChanges();
     }
     return(true);
 }
示例#7
0
        public bool CreateBusinessFlowAttributes(Domain.Entity entity)
        {
            var existAttributes = _attributeRepository.Query(f => f.EntityId == entity.EntityId && f.Name.In("StageId"));

            if (existAttributes != null && existAttributes.Count() == 1)
            {
                return(true);
            }
            var attr = new Domain.Attribute()
            {
                AttributeId = Guid.NewGuid(), EntityId = entity.EntityId, Name = "StageId", LocalizedName = _loc["entity_sys_processstage"], AttributeTypeName = AttributeTypeIds.UNIQUEIDENTIFIER, EntityName = entity.Name, IsNullable = true, IsRequired = false, LogEnabled = false, IsCustomizable = false, IsCustomField = false
            };

            return(Create(attr));
        }
示例#8
0
        public bool Update(Domain.Entity entity)
        {
            var oldEntity = _entityRepository.FindById(entity.EntityId);

            if (oldEntity == null)
            {
                return(false);
            }
            var result = true;

            if (!oldEntity.IsCustomizable)
            {
                entity.AuthorizationEnabled = oldEntity.AuthorizationEnabled;
                entity.WorkFlowEnabled      = oldEntity.WorkFlowEnabled;
                entity.BusinessFlowEnabled  = oldEntity.BusinessFlowEnabled;
                entity.EntityMask           = oldEntity.EntityMask;
            }
            using (UnitOfWork.Build(_entityRepository.DbContext))
            {
                result = _entityRepository.Update(entity);
                //从组织范围改成用户范围
                if (oldEntity.EntityMask != entity.EntityMask && entity.EntityMask == EntityMaskEnum.User)
                {
                    //创建所有者字段
                    _attributeCreater.CreateOwnerAttributes(entity);
                }
                //启用审批流,创建相关字段
                if (!oldEntity.WorkFlowEnabled && entity.WorkFlowEnabled)
                {
                    _attributeCreater.CreateWorkFlowAttributes(entity);
                }
                //启用业务流,创建相关字段
                if (!oldEntity.BusinessFlowEnabled && entity.BusinessFlowEnabled)
                {
                    _attributeCreater.CreateBusinessFlowAttributes(entity);
                }
                //localization
                _localizedLabelService.Update(entity.LocalizedName.IfEmpty(""), "LocalizedName", entity.EntityId, _appContext.BaseLanguage);
                _localizedLabelService.Update(entity.Description.IfEmpty(""), "Description", entity.EntityId, _appContext.BaseLanguage);

                //set to cache
                _cacheService.SetEntity(entity);
            }
            return(result);
        }
示例#9
0
        public bool CreateOwnerAttributes(Domain.Entity entity)
        {
            var existAttributes = _attributeRepository.Query(f => f.EntityId == entity.EntityId && f.Name.In("OwnerId", "OwnerIdType", "OwningBusinessUnit"));

            if (existAttributes != null && existAttributes.Count() == 3)
            {
                return(true);
            }
            var systemUserPrimaryKey         = _attributeRepository.Find(x => x.EntityName == "SystemUser" && x.Name == "SystemUserId");
            var businessUnitPrimaryKey       = _attributeRepository.Find(x => x.EntityName == "BusinessUnit" && x.Name == "BusinessUnitId");
            List <Domain.Attribute> attrList = new List <Domain.Attribute>();

            if (!existAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("OwnerId")))
            {
                attrList.Add(new Domain.Attribute()
                {
                    AttributeId = Guid.NewGuid(), EntityId = entity.EntityId, Name = "OwnerId", LocalizedName = _loc["entity_sys_ownerid"], AttributeTypeName = AttributeTypeIds.OWNER, EntityName = entity.Name, ReferencedEntityId = systemUserPrimaryKey.EntityId, IsNullable = false, IsRequired = true, LogEnabled = false, IsCustomizable = false, IsCustomField = false
                });
            }
            if (!existAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("OwnerIdType")))
            {
                attrList.Add(new Domain.Attribute()
                {
                    AttributeId = Guid.NewGuid(), EntityId = entity.EntityId, Name = "OwnerIdType", LocalizedName = _loc["entity_sys_owneridtype"], AttributeTypeName = AttributeTypeIds.INT, EntityName = entity.Name, IsNullable = false, IsRequired = true, LogEnabled = false, IsCustomizable = false, IsCustomField = false
                });
            }
            if (!existAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("OwningBusinessUnit")))
            {
                attrList.Add(new Domain.Attribute()
                {
                    AttributeId = Guid.NewGuid(), EntityId = entity.EntityId, Name = "OwningBusinessUnit", LocalizedName = _loc["entity_sys_owningbusinessunit"], AttributeTypeName = AttributeTypeIds.LOOKUP, EntityName = entity.Name, ReferencedEntityId = businessUnitPrimaryKey.EntityId, IsNullable = true, IsRequired = true, LogEnabled = false, IsCustomizable = false, IsCustomField = false
                });
            }
            foreach (var attr in attrList)
            {
                Create(attr);
            }
            return(true);
        }
示例#10
0
        public bool CreateDefaultAttributes(Domain.Entity entity, params string[] defaultAttributeNames)
        {
            var result     = true;
            var attributes = _defaultAttributeProvider.GetSysAttributes(entity).Where(x => defaultAttributeNames.Contains(x.Name, StringComparer.InvariantCultureIgnoreCase)).ToList();

            using (UnitOfWork.Build(_attributeRepository.DbContext))
            {
                result = _attributeRepository.CreateMany(attributes);
                //新建字段选项
                var stateCodeAttr = attributes.Find(n => n.Name.IsCaseInsensitiveEqual("statecode"));
                if (stateCodeAttr != null)
                {
                    result = _stringMapCreater.CreateMany(stateCodeAttr.PickLists);
                }
                var statusCodeAttr = attributes.Find(n => n.Name.IsCaseInsensitiveEqual("statuscode"));
                if (statusCodeAttr != null)
                {
                    _optionSetCreater.Create(statusCodeAttr.OptionSet);
                }
                //创建关系
                result = _relationShipCreater.CreateMany(_defaultAttributeProvider.GetSysAttributeRelationShips(entity, attributes));
                //attribute localization
                foreach (var attr in attributes)
                {
                    var label = attr.TypeIsPrimaryKey() ? entity.LocalizedName : _loc["entity_sys_" + attr.Name];
                    _localizedLabelService.Append(entity.SolutionId, label, AttributeDefaults.ModuleName, "LocalizedName", attr.AttributeId)
                    .Append(entity.SolutionId, label, AttributeDefaults.ModuleName, "Description", attr.AttributeId);
                }
                _localizedLabelService.Save();
                //add to cache
                foreach (var attr in attributes)
                {
                    _cacheService.SetEntity(attr);
                }
            }
            return(result);
        }
示例#11
0
        public void CreateTable(Domain.Entity entity, List <Domain.Attribute> defaultAttributes)
        {
            if (this.TableExists(entity.Name))
            {
                return;
            }
            Sql s = Sql.Builder.Append(string.Format("CREATE TABLE [dbo].[{0}]", entity.Name))
                    .Append("(");

            //.Append(string.Format("[{0}Id] [uniqueidentifier] NOT NULL,", entity.Name))
            //.Append("[Name] [nvarchar](300) NULL,")
            //.Append("[VersionNumber] [timestamp] NOT NULL,")
            //.Append("[CreatedOn] [datetime] NOT NULL,")
            //.Append("[CreatedBy] [uniqueidentifier] NOT NULL,")
            //.Append("[ModifiedOn] [datetime] NULL,")
            //.Append("[ModifiedBy] [uniqueidentifier] NULL,")
            //.Append("[StateCode] [int] NOT NULL,")
            //.Append("[StatusCode] [int] NOT NULL,");
            foreach (var attribute in defaultAttributes)
            {
                s.Append("[{0}] {1} {2} NULL,".FormatWith(attribute.Name, attribute.GetDbType(), attribute.IsNullable ? "" : "NOT"));
            }
            List <string> idxColumns = new List <string>();//需要创建索引的字段

            if (defaultAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("StateCode")))
            {
                idxColumns.Add("StateCode");
            }
            if (defaultAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("CreatedOn")))
            {
                idxColumns.Add("CreatedOn");
            }
            if (entity.EntityMask == EntityMaskEnum.User)
            {
                //s.Append("[OwnerId] [uniqueidentifier] NOT NULL,")
                //.Append("[OwnerIdType] [int] NOT NULL,")
                //.Append("[OwningBusinessUnit] [uniqueidentifier] NULL,");
                if (defaultAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("OwnerId")))
                {
                    if (!defaultAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("OwnerIdType")))
                    {
                        s.Append("[OwnerIdType] [int] NOT NULL,");
                    }
                    idxColumns.Add("OwnerId");
                }
            }
            if (defaultAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("OrganizationId")))
            {
                //s.Append("[OrganizationId] [uniqueidentifier] NOT NULL,");
                idxColumns.Add("OrganizationId");
            }
            //if (entity.WorkFlowEnabled)
            //{
            //    s.Append("[WorkFlowId] [uniqueidentifier] NULL,");
            //    s.Append("[ProcessState] [int] NULL default(-1),");
            //}
            //if (entity.BusinessFlowEnabled)
            //{
            //    s.Append("[StageId] [uniqueidentifier] NULL,");
            //}
            //主键
            s.Append(string.Format("CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED", entity.Name))
            .Append("(")
            .Append(string.Format("[{0}Id] ASC", entity.Name))
            .Append(")WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON[PRIMARY]")
            .Append(") ON [PRIMARY]");
            //创建外键约束
            if (defaultAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("CreatedBy")))
            {
                s.Append(string.Format("ALTER TABLE [dbo].[{0}]  WITH CHECK ADD  CONSTRAINT [FK_{0}_SystemUser_CreatedBy] FOREIGN KEY([CreatedBy])", entity.Name));
                s.Append("REFERENCES[dbo].[SystemUser]([SystemUserId])");
                s.Append(string.Format("ALTER TABLE [dbo].[{0}] CHECK CONSTRAINT [FK_{0}_SystemUser_CreatedBy]", entity.Name));
            }
            if (entity.EntityMask == EntityMaskEnum.User)
            {
                if (defaultAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("OwningBusinessUnit")))
                {
                    s.Append(string.Format("ALTER TABLE [dbo].[{0}]  WITH NOCHECK ADD  CONSTRAINT [FK_{0}_BusinessUnit_OwningBusinessUnit] FOREIGN KEY([OwningBusinessUnit])", entity.Name));
                    s.Append("REFERENCES[dbo].[BusinessUnit]([BusinessUnitId])");
                    s.Append(string.Format("ALTER TABLE [dbo].[{0}] CHECK CONSTRAINT [FK_{0}_BusinessUnit_OwningBusinessUnit]", entity.Name));
                }
            }
            if (defaultAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("OrganizationId")))
            {
                s.Append(string.Format("ALTER TABLE [dbo].[{0}]  WITH NOCHECK ADD  CONSTRAINT [FK_{0}_Organization_OrganizationId] FOREIGN KEY([OrganizationId])", entity.Name));
                s.Append("REFERENCES[dbo].[Organization]([OrganizationId])");
                s.Append(string.Format("ALTER TABLE [dbo].[{0}] CHECK CONSTRAINT [FK_{0}_Organization_OrganizationId]", entity.Name));
            }

            //启动流程时建立约束
            if (entity.WorkFlowEnabled)
            {
                if (defaultAttributes.Exists(x => x.Name.IsCaseInsensitiveEqual("WorkFlowId")))
                {
                    s.Append(string.Format("ALTER TABLE [dbo].[{0}]  WITH NOCHECK ADD  CONSTRAINT [FK_{0}_WorkFlow_WorkFlowId] FOREIGN KEY([WorkFlowId])", entity.Name));
                    s.Append("REFERENCES[dbo].[WorkFlow]([WorkFlowId])");
                    s.Append(string.Format("ALTER TABLE [dbo].[{0}] CHECK CONSTRAINT [FK_{0}_WorkFlow_WorkFlowId]", entity.Name));
                }
            }
            //创建默认字段索引
            if (idxColumns.NotEmpty())
            {
                s.Append(string.Format("CREATE INDEX ndx_core ON {0}({1}) WITH (FILLFACTOR = 80)", entity.Name, string.Join(",", idxColumns)));
            }

            _database.Execute(s);
        }
示例#12
0
        public List <Domain.RelationShip> GetSysAttributeRelationShips(Domain.Entity entity, List <Domain.Attribute> sysAttributes)
        {
            var primaryFields          = _attributeFinder.Query(x => x.Where(f => f.EntityName.In("SystemUser", "BusinessUnit", "Organization", "WorkFlow") && f.Name.In("SystemUserId", "BusinessUnitId", "OrganizationId", "WorkFlowId")));
            var systemUserPrimaryKey   = primaryFields.Find(x => x.Name == "SystemUserId");
            var businessUnitPrimaryKey = primaryFields.Find(x => x.Name == "BusinessUnitId");
            var organizationPrimaryKey = primaryFields.Find(x => x.Name == "OrganizationId");
            var workFlowPrimaryKey     = primaryFields.Find(x => x.Name == "WorkFlowId");
            List <Domain.RelationShip> relationships = new List <Domain.RelationShip>();

            if (sysAttributes.Exists(n => n.Name.IsCaseInsensitiveEqual("CreatedBy")))
            {
                var createdByRelationShip = new Domain.RelationShip
                {
                    Name                     = "lk_" + entity.Name + "_createdby",
                    RelationshipType         = RelationShipType.ManyToOne,
                    ReferencingAttributeId   = sysAttributes.Find(n => n.Name.IsCaseInsensitiveEqual("CreatedBy")).AttributeId,
                    ReferencingAttributeName = "CreatedBy",
                    ReferencedEntityName     = "SystemUser",
                    ReferencedAttributeName  = "SystemUserId",
                    ReferencingEntityId      = entity.EntityId,
                    ReferencedAttributeId    = systemUserPrimaryKey.AttributeId,
                    ReferencedEntityId       = systemUserPrimaryKey.EntityId
                };
                relationships.Add(createdByRelationShip);
            }
            if (sysAttributes.Exists(n => n.Name.IsCaseInsensitiveEqual("ModifiedBy")))
            {
                var modifiedByRelationShip = new Domain.RelationShip
                {
                    Name                     = "lk_" + entity.Name + "_modifiedby",
                    RelationshipType         = RelationShipType.ManyToOne,
                    ReferencingAttributeId   = sysAttributes.Find(n => n.Name == "ModifiedBy").AttributeId,
                    ReferencingAttributeName = "ModifiedBy",
                    ReferencedEntityName     = "SystemUser",
                    ReferencedAttributeName  = "SystemUserId",
                    ReferencingEntityId      = entity.EntityId,
                    ReferencedAttributeId    = systemUserPrimaryKey.AttributeId,
                    ReferencedEntityId       = systemUserPrimaryKey.EntityId
                };
                relationships.Add(modifiedByRelationShip);
            }
            if (entity.EntityMask == EntityMaskEnum.User)
            {
                if (sysAttributes.Exists(n => n.Name.IsCaseInsensitiveEqual("OwnerId")))
                {
                    var ownerIdRelationShip = new Domain.RelationShip
                    {
                        Name                     = "lk_" + entity.Name + "_ownerid",
                        RelationshipType         = RelationShipType.ManyToOne,
                        ReferencingAttributeId   = sysAttributes.Find(n => n.Name.IsCaseInsensitiveEqual("OwnerId")).AttributeId,
                        ReferencingAttributeName = "OwnerId",
                        ReferencedEntityName     = "SystemUser",
                        ReferencedAttributeName  = "SystemUserId",
                        ReferencingEntityId      = entity.EntityId,
                        ReferencedAttributeId    = systemUserPrimaryKey.AttributeId,
                        ReferencedEntityId       = systemUserPrimaryKey.EntityId
                    };
                    relationships.Add(ownerIdRelationShip);
                }
                if (sysAttributes.Exists(n => n.Name.IsCaseInsensitiveEqual("OwningBusinessUnit")))
                {
                    var owningBusinessUnitRelationShip = new Domain.RelationShip
                    {
                        Name                     = "lk_" + entity.Name + "_owningbusinessunit",
                        RelationshipType         = RelationShipType.ManyToOne,
                        ReferencingAttributeId   = sysAttributes.Find(n => n.Name.IsCaseInsensitiveEqual("OwningBusinessUnit")).AttributeId,
                        ReferencingAttributeName = "OwningBusinessUnit",
                        ReferencedEntityName     = "BusinessUnit",
                        ReferencedAttributeName  = "BusinessUnitId",
                        ReferencingEntityId      = entity.EntityId,
                        ReferencedAttributeId    = businessUnitPrimaryKey.AttributeId,
                        ReferencedEntityId       = businessUnitPrimaryKey.EntityId
                    };
                    relationships.Add(owningBusinessUnitRelationShip);
                }
            }
            if (sysAttributes.Exists(n => n.Name.IsCaseInsensitiveEqual("OrganizationId")))
            {
                var organizationIdRelationShip = new Domain.RelationShip
                {
                    Name                     = "lk_" + entity.Name + "_organizationid",
                    RelationshipType         = RelationShipType.ManyToOne,
                    ReferencingAttributeId   = sysAttributes.Find(n => n.Name.IsCaseInsensitiveEqual("OrganizationId")).AttributeId,
                    ReferencingAttributeName = "OrganizationId",
                    ReferencedEntityName     = "Organization",
                    ReferencedAttributeName  = "OrganizationId",
                    ReferencingEntityId      = entity.EntityId,
                    ReferencedAttributeId    = organizationPrimaryKey.AttributeId,
                    ReferencedEntityId       = organizationPrimaryKey.EntityId
                };
                relationships.Add(organizationIdRelationShip);
            }
            if (entity.WorkFlowEnabled)
            {
                if (sysAttributes.Exists(n => n.Name.IsCaseInsensitiveEqual("WorkFlowId")))
                {
                    var workflowIdRelationShip = new Domain.RelationShip
                    {
                        Name                     = "lk_" + entity.Name + "_workflowid",
                        RelationshipType         = RelationShipType.ManyToOne,
                        ReferencingAttributeId   = sysAttributes.Find(n => n.Name.IsCaseInsensitiveEqual("WorkFlowId")).AttributeId,
                        ReferencingAttributeName = "WorkFlowId",
                        ReferencedEntityName     = "WorkFlow",
                        ReferencedAttributeName  = "WorkFlowId",
                        ReferencingEntityId      = entity.EntityId,
                        ReferencedAttributeId    = workFlowPrimaryKey.AttributeId,
                        ReferencedEntityId       = workFlowPrimaryKey.EntityId
                    };
                    relationships.Add(workflowIdRelationShip);
                }
            }
            return(relationships);
        }
示例#13
0
        public List <Domain.Attribute> GetSysAttributes(Domain.Entity entity)
        {
            var primaryFields          = _attributeFinder.Query(x => x.Where(f => f.EntityName.In("SystemUser", "BusinessUnit", "Organization", "WorkFlow") && f.Name.In("SystemUserId", "BusinessUnitId", "OrganizationId", "WorkFlowId")));
            var systemUserPrimaryKey   = primaryFields.Find(x => x.Name == "SystemUserId");
            var businessUnitPrimaryKey = primaryFields.Find(x => x.Name == "BusinessUnitId");
            var organizationPrimaryKey = primaryFields.Find(x => x.Name == "OrganizationId");
            var workFlowPrimaryKey     = primaryFields.Find(x => x.Name == "WorkFlowId");
            //插入自动创建的字段
            List <Domain.Attribute> attrList = new List <Domain.Attribute>();
            var primaryAttr = new Domain.Attribute
            {
                EntityId          = entity.EntityId,
                Name              = entity.Name + "Id",
                LocalizedName     = entity.LocalizedName,
                AttributeTypeName = AttributeTypeIds.PRIMARYKEY,
                EntityName        = entity.Name,
                IsNullable        = false,
                IsRequired        = true,
                LogEnabled        = false,
                DefaultValue      = "newid()",
                IsCustomizable    = false,
                IsCustomField     = false,
                CreatedBy         = _currentUser.SystemUserId
            };

            attrList.Add(primaryAttr);
            var nameAttr = new Domain.Attribute
            {
                EntityId          = entity.EntityId,
                Name              = "Name",
                LocalizedName     = _loc["entity_sys_name"],
                AttributeTypeName = AttributeTypeIds.NVARCHAR,
                EntityName        = entity.Name,
                IsNullable        = true,
                IsRequired        = true,
                LogEnabled        = false,
                MaxLength         = 300,
                IsCustomField     = false,
                IsPrimaryField    = true,
                CreatedBy         = _currentUser.SystemUserId
            };

            attrList.Add(nameAttr);
            var vnAttr = new Domain.Attribute
            {
                EntityId          = entity.EntityId,
                Name              = "VersionNumber",
                LocalizedName     = _loc["entity_sys_versionnumber"],
                AttributeTypeName = AttributeTypeIds.TIMESTAMP,
                EntityName        = entity.Name,
                IsNullable        = false,
                IsRequired        = true,
                LogEnabled        = false,
                IsCustomizable    = false,
                IsCustomField     = false,
                CreatedBy         = _currentUser.SystemUserId
            };

            attrList.Add(vnAttr);
            var createdOnAttr = new Domain.Attribute
            {
                EntityId          = entity.EntityId,
                Name              = "CreatedOn",
                LocalizedName     = _loc["entity_sys_createdon"],
                AttributeTypeName = AttributeTypeIds.DATETIME,
                EntityName        = entity.Name,
                IsNullable        = false,
                IsRequired        = true,
                LogEnabled        = false,
                IsCustomizable    = false,
                IsCustomField     = false,
                CreatedBy         = _currentUser.SystemUserId
            };

            attrList.Add(createdOnAttr);
            var createdByAttr = new Domain.Attribute
            {
                EntityId           = entity.EntityId,
                Name               = "CreatedBy",
                LocalizedName      = _loc["entity_sys_createdby"],
                AttributeTypeName  = AttributeTypeIds.LOOKUP,
                EntityName         = entity.Name,
                ReferencedEntityId = systemUserPrimaryKey.EntityId,
                IsNullable         = false,
                IsRequired         = true,
                LogEnabled         = false,
                IsCustomizable     = false,
                IsCustomField      = false,
                CreatedBy          = _currentUser.SystemUserId
            };

            attrList.Add(createdByAttr);
            var modifiedOnAttr = new Domain.Attribute
            {
                EntityId          = entity.EntityId,
                Name              = "ModifiedOn",
                LocalizedName     = _loc["entity_sys_modifiedon"],
                AttributeTypeName = AttributeTypeIds.DATETIME,
                EntityName        = entity.Name,
                IsNullable        = true,
                IsRequired        = false,
                LogEnabled        = false,
                IsCustomizable    = false,
                IsCustomField     = false,
                CreatedBy         = _currentUser.SystemUserId
            };

            attrList.Add(modifiedOnAttr);
            var modifiedByAttr = new Domain.Attribute
            {
                EntityId           = entity.EntityId,
                Name               = "ModifiedBy",
                LocalizedName      = _loc["entity_sys_modifiedby"],
                AttributeTypeName  = AttributeTypeIds.LOOKUP,
                EntityName         = entity.Name,
                ReferencedEntityId = systemUserPrimaryKey.EntityId,
                IsNullable         = true,
                IsRequired         = false,
                LogEnabled         = false,
                IsCustomizable     = false,
                IsCustomField      = false,
                CreatedBy          = _currentUser.SystemUserId
            };

            attrList.Add(modifiedByAttr);

            #region 状态字段

            var stateCodeAttr = new Domain.Attribute
            {
                EntityId          = entity.EntityId,
                Name              = "StateCode",
                LocalizedName     = _loc["entity_sys_statecode"],
                AttributeTypeName = AttributeTypeIds.STATE,
                EntityName        = entity.Name,
                IsNullable        = false,
                IsRequired        = true,
                LogEnabled        = false,
                IsCustomizable    = false,
                IsCustomField     = false,
                CreatedBy         = _currentUser.SystemUserId
            };
            List <Domain.StringMap> statePicklist = new List <Domain.StringMap>();
            var stateCodeMap = new Domain.StringMap
            {
                StringMapId   = Guid.NewGuid(),
                AttributeId   = stateCodeAttr.AttributeId,
                Name          = _loc["enabled"],
                Value         = 1,
                DisplayOrder  = 0,
                AttributeName = "StateCode",
                EntityName    = entity.Name
            };
            statePicklist.Add(stateCodeMap);
            var stateCodeMap2 = new Domain.StringMap
            {
                StringMapId   = Guid.NewGuid(),
                AttributeId   = stateCodeAttr.AttributeId,
                Name          = _loc["disabled"],
                Value         = 0,
                DisplayOrder  = 1,
                AttributeName = "StateCode",
                EntityName    = entity.Name
            };
            statePicklist.Add(stateCodeMap2);
            stateCodeAttr.PickLists = statePicklist;
            attrList.Add(stateCodeAttr);

            #endregion 状态字段

            #region 状态描述字段

            var statusCodeAttr = new Domain.Attribute
            {
                EntityId          = entity.EntityId,
                Name              = "StatusCode",
                LocalizedName     = _loc["entity_sys_statuscode"],
                AttributeTypeName = AttributeTypeIds.STATUS,
                EntityName        = entity.Name,
                IsNullable        = false,
                IsRequired        = true,
                LogEnabled        = false,
                IsCustomizable    = false,
                IsCustomField     = false,
                DefaultValue      = "0",
                CreatedBy         = _currentUser.SystemUserId
            };

            var os = new Domain.OptionSet
            {
                ComponentState = entity.ComponentState,
                SolutionId     = entity.SolutionId,
                CreatedBy      = statusCodeAttr.CreatedBy,
                IsPublic       = false,
                Name           = statusCodeAttr.LocalizedName
            };
            var osDetail1 = new Domain.OptionSetDetail
            {
                DisplayOrder = 0,
                IsSelected   = false,
                Name         = _loc["attribute_statuscode_draft"],
                Value        = 0,
                OptionSetId  = os.OptionSetId
            };
            var osDetail2 = new Domain.OptionSetDetail
            {
                DisplayOrder = 1,
                IsSelected   = false,
                Name         = _loc["attribute_statuscode_actived"],
                Value        = 1,
                OptionSetId  = os.OptionSetId
            };
            var osDetail3 = new Domain.OptionSetDetail
            {
                DisplayOrder = 2,
                IsSelected   = false,
                Name         = _loc["attribute_statuscode_invalid"],
                Value        = 2,
                OptionSetId  = os.OptionSetId
            };
            os.Items = new List <Domain.OptionSetDetail>()
            {
                osDetail1, osDetail2, osDetail3
            };
            statusCodeAttr.OptionSet   = os;
            statusCodeAttr.OptionSetId = os.OptionSetId;
            attrList.Add(statusCodeAttr);

            #endregion 状态描述字段

            //实体范围
            if (entity.EntityMask == EntityMaskEnum.User)
            {
                var ownerIdAttr = new Domain.Attribute
                {
                    EntityId           = entity.EntityId,
                    Name               = "OwnerId",
                    LocalizedName      = _loc["entity_sys_ownerid"],
                    AttributeTypeName  = AttributeTypeIds.OWNER,
                    EntityName         = entity.Name,
                    ReferencedEntityId = systemUserPrimaryKey.EntityId,
                    IsNullable         = false,
                    IsRequired         = true,
                    LogEnabled         = false,
                    IsCustomizable     = false,
                    IsCustomField      = false
                };
                attrList.Add(ownerIdAttr);
                var ownerIdTypeAttr = new Domain.Attribute
                {
                    EntityId          = entity.EntityId,
                    Name              = "OwnerIdType",
                    LocalizedName     = _loc["entity_sys_owneridtype"],
                    AttributeTypeName = AttributeTypeIds.INT,
                    EntityName        = entity.Name,
                    IsNullable        = false,
                    IsRequired        = true,
                    LogEnabled        = false,
                    IsCustomizable    = false,
                    IsCustomField     = false
                };
                attrList.Add(ownerIdTypeAttr);
                var owningBusinessUnitAttr = new Domain.Attribute
                {
                    EntityId           = entity.EntityId,
                    Name               = "OwningBusinessUnit",
                    LocalizedName      = _loc["entity_sys_owningbusinessunit"],
                    AttributeTypeName  = AttributeTypeIds.LOOKUP,
                    EntityName         = entity.Name,
                    ReferencedEntityId = businessUnitPrimaryKey.EntityId,
                    IsNullable         = true,
                    IsRequired         = true,
                    LogEnabled         = false,
                    IsCustomizable     = false,
                    IsCustomField      = false
                };
                attrList.Add(owningBusinessUnitAttr);
            }
            var organizationIdAttr = new Domain.Attribute
            {
                EntityId           = entity.EntityId,
                Name               = "OrganizationId",
                LocalizedName      = _loc["entity_sys_organizationid"],
                AttributeTypeName  = AttributeTypeIds.LOOKUP,
                EntityName         = entity.Name,
                ReferencedEntityId = organizationPrimaryKey.EntityId,
                IsNullable         = false,
                IsRequired         = true,
                LogEnabled         = false,
                IsCustomizable     = false,
                IsCustomField      = false
            };
            attrList.Add(organizationIdAttr);
            //启用审批流
            if (entity.WorkFlowEnabled)
            {
                var workflowIdAttr = new Domain.Attribute
                {
                    EntityId           = entity.EntityId,
                    Name               = "WorkFlowId",
                    LocalizedName      = _loc["entity_sys_workflowid"],
                    AttributeTypeName  = AttributeTypeIds.LOOKUP,
                    EntityName         = entity.Name,
                    ReferencedEntityId = workFlowPrimaryKey.EntityId,
                    IsNullable         = true,
                    IsRequired         = false,
                    LogEnabled         = false,
                    IsCustomizable     = false,
                    IsCustomField      = false
                };
                attrList.Add(workflowIdAttr);
                var processStateAttr = new Domain.Attribute
                {
                    EntityId          = entity.EntityId,
                    Name              = "ProcessState",
                    LocalizedName     = _loc["entity_sys_processstate"],
                    AttributeTypeName = AttributeTypeIds.PICKLIST,
                    EntityName        = entity.Name,
                    OptionSetId       = Guid.Parse("00000000-0000-0000-0000-000000000001"),
                    IsNullable        = true,
                    IsRequired        = false,
                    LogEnabled        = false,
                    IsCustomizable    = false,
                    IsCustomField     = false,
                    DefaultValue      = "-1"
                };
                attrList.Add(processStateAttr);
            }
            //启用业务流程
            if (entity.BusinessFlowEnabled)
            {
                var stageIdAttr = new Domain.Attribute
                {
                    EntityId          = entity.EntityId,
                    Name              = "StageId",
                    LocalizedName     = _loc["entity_sys_processstage"],
                    AttributeTypeName = AttributeTypeIds.UNIQUEIDENTIFIER,
                    EntityName        = entity.Name,
                    IsNullable        = true,
                    IsRequired        = false,
                    LogEnabled        = false,
                    IsCustomizable    = false,
                    IsCustomField     = false
                };
                attrList.Add(stageIdAttr);
            }
            return(attrList);
        }
示例#14
0
 public bool Import(Guid solutionId, Domain.Entity entity, List <Domain.Attribute> attributes)
 {
     if (attributes.NotEmpty())
     {
         foreach (var attr in attributes)
         {
             attr.EntityId   = entity.EntityId;
             attr.EntityName = entity.Name;
             var existAttr = _attributeFinder.Find(attr.EntityId, attr.Name);
             var isCreate  = existAttr == null;
             if (!isCreate)
             {
                 existAttr.DataFormat    = attr.DataFormat;
                 existAttr.DefaultValue  = attr.DefaultValue;
                 existAttr.DisplayStyle  = attr.DisplayStyle;
                 existAttr.LogEnabled    = attr.LogEnabled;
                 existAttr.IsRequired    = attr.IsRequired;
                 existAttr.LocalizedName = attr.LocalizedName;
                 existAttr.MaxLength     = attr.MaxLength;
                 existAttr.MaxValue      = attr.MaxValue;
                 existAttr.MinValue      = attr.MinValue;
                 existAttr.Precision     = attr.Precision;
                 _attributeUpdater.Update(existAttr);
             }
             else
             {
                 attr.IsCustomField  = true;
                 attr.IsCustomizable = true;
                 attr.CreatedBy      = _appContext.GetFeature <ICurrentUser>().SystemUserId;
                 _attributeCreater.Create(attr);
             }
             //字段选项
             //if (attr.TypeIsBit() || attr.TypeIsState())
             //{
             //    if (isCreate)
             //    {
             //        foreach (var s in attr.PickLists)
             //        {
             //            s.AttributeId = attr.AttributeId;
             //            s.AttributeName = attr.Name;
             //            s.EntityName = item.Name;
             //        }
             //        _stringMapService.CreateMany(attr.PickLists);
             //    }
             //    else
             //    {
             //        foreach (var s in attr.PickLists)
             //        {
             //            var smap = _stringMapService.FindById(s.StringMapId);
             //            if (smap != null)
             //            {
             //                smap.Name = s.Name;
             //                _stringMapService.Update(smap);
             //            }
             //        }
             //    }
             //}
         }
     }
     return(true);
 }
示例#15
0
 public static string GetIdName(this Domain.Entity entity)
 {
     return($"{entity.Name}Id");
 }
 public bool Post(Domain.Entity myEntity)
 {
     log.Debug("MyController Post Method");
     return(_entityManager.SaveMyEntity(myEntity));
 }
示例#17
0
 public bool Create(Domain.Entity entity, bool makeAllDefaultAttributes = true)
 {
     return(this.Create(entity, AttributeDefaults.SystemAttributes));
 }
示例#18
0
 public static string BuildKey(Domain.Entity entity)
 {
     return(entity.EntityId + "/" + entity.Name + "/");
 }
示例#19
0
        public override Evaluant.Uss.Commands.CreateReferenceCommand Visit(Evaluant.Uss.Commands.CreateReferenceCommand item)
        {
            Mapping.Reference reference = engine.Provider.Mapping.Entities[item.ParentEntity.Type].References[item.Role ?? item.Reference.Name];
            if (commands.ContainsKey(item.ParentEntity) && item.Reference.Cardinality is Cardinality.ToOne)
            {
                Domain.Entity key = new Domain.Entity(item.ParentEntity.Type);
                IDbStatement command;
                if (reference.IsComposite)
                {
                    command = commands[item.ParentEntity];
                    IDbStatement childStatement;
                    if (commands.TryGetValue(item.ChildEntity, out childStatement))
                    {
                        foreach (DbParameter parameter in childStatement.Parameters.Values)
                        {
                            if (!command.Parameters.ContainsKey(parameter.Name))
                                command.Add(parameter);
                        }
                        commands[item.ChildEntity] = command;
                    }
                }
                else
                    command = engine.Provider.Mapping.Mapper.Create(reference, ((InsertStatement)commands[item.ParentEntity]).Identity);
                commands.Add(key, command);
                for (int i = 0; i < reference.Rules.Count; i++)
                {
                    Mapping.Rule rule = reference.Rules[i];
                    if (rule.ParentTable == reference.Parent.Table && reference.Model.Cardinality.IsOne)
                    {
                        for (int fieldNumber = 0; fieldNumber < rule.ParentFields.Count; fieldNumber++)
                        {
                            Field parentField = rule.ParentFields[fieldNumber];
                            Field childField = rule.ChildFields[fieldNumber];
                            Mapping.Attribute attribute = null;
                            foreach (Mapping.Attribute a in reference.Target.Attributes.Values)
                            {
                                if (a.Field == childField)
                                {
                                    attribute = a;
                                    break;
                                }
                            }
                            AddParameter(command, parentField, item.ChildEntity[attribute.Name]);
                        }
                    }
                    if (rule.ChildTable == reference.Target.Table && reference.Model.Cardinality is Cardinality.ToOne)
                    {
                        for (int fieldNumber = 0; fieldNumber < rule.ParentFields.Count; fieldNumber++)
                        {
                            Field parentField = rule.ParentFields[fieldNumber];
                            Field childField = rule.ChildFields[fieldNumber];
                            Mapping.Attribute attribute = null;
                            foreach (Mapping.Attribute a in reference.Target.Attributes.Values)
                            {
                                if (a.Field == childField)
                                {
                                    attribute = a;
                                    break;
                                }
                            }
                            if (attribute != null)
                                AddParameter(command, parentField, item.ChildEntity[attribute.Name].Value);
                        }
                        foreach (Mapping.Attribute attribute in reference.Parent.Ids.Values)
                        {
                            AddParameter(command, attribute, item.ParentEntity[attribute.Name].Value);
                        }
                    }
                }
            }
            if (item.Reference.Cardinality.IsMany && item.Reference.Cardinality is Cardinality.ToMany)
            {
                Domain.Entity key = new Domain.Entity(item.ParentEntity.Type);
                IDbStatement command = engine.Provider.Mapping.Mapper.Create(reference);
                commands.Add(key, command);
                Table indexTable = reference.Rules[0].ChildTable;
                for (int i = 0; i < reference.Rules.Count; i++)
                {
                    Mapping.Rule rule = reference.Rules[i];
                    if (rule.ParentTable == indexTable)
                    {
                        for (int fieldNumber = 0; fieldNumber < rule.ParentFields.Count; fieldNumber++)
                        {
                            Field parentField = rule.ParentFields[fieldNumber];
                            Field childField = rule.ChildFields[fieldNumber];
                            Mapping.Attribute attribute = null;
                            foreach (Mapping.Attribute a in reference.Target.Attributes.Values)
                            {
                                if (a.Field == childField)
                                {
                                    attribute = a;
                                    break;
                                }
                            }
                            IDbStatement statement;
                            if (commands.TryGetValue(item.ChildEntity, out statement))
                            {
                                InsertStatement insert = statement as InsertStatement;
                                if (insert != null && insert.Identity != null)
                                    command.Add(new LazyParameter(parentField.ColumnName.Text, insert.Identity, ParameterDirection.Input));
                                else
                                    AddParameter(command, parentField, item.ChildEntity[attribute.Name].Value);
                            }
                            else
                                AddParameter(command, parentField, item.ChildEntity[attribute.Name].Value);
                        }
                    }
                    if (rule.ChildTable == indexTable)
                    {
                        for (int fieldNumber = 0; fieldNumber < rule.ParentFields.Count; fieldNumber++)
                        {
                            Field parentField = rule.ParentFields[fieldNumber];
                            Field childField = rule.ChildFields[fieldNumber];
                            Mapping.Attribute attribute = null;
                            foreach (Mapping.Attribute a in reference.Parent.Attributes.Values)
                            {
                                if (a.Field == parentField)
                                {
                                    attribute = a;
                                    break;
                                }
                            }
                            IDbStatement statement;
                            if (commands.TryGetValue(item.ParentEntity, out statement))
                            {
                                InsertStatement insert = statement as InsertStatement;
                                if (insert != null && insert.Identity != null)
                                {
                                    command.Add(new LazyParameter(childField.ColumnName.Text, insert.Identity, ParameterDirection.Input));
                                }
                                else
                                    AddParameter(command, childField, item.ParentEntity[attribute.Name].Value);
                            }
                            else
                                AddParameter(command, childField, item.ParentEntity[attribute.Name].Value);
                        }
                    }

                }

                //foreach (Mapping.Field field in engine.Mapping.Entities[item.ParentEntity.Type].References[item.Role.Name].Fields)
                //{
                //    if (field.ParentEntity.Type == item.ParentEntity.Type)
                //    {
                //        //insertEntities[item.ParentEntity].Values.Add(new ColumnExpression(null,field.ColumnName),item.ChildEntity.Entries[
                //    }
                //}
            }

            return item;
        }