public IActionResult Post(CreateRecordModel model) { if (model.Data.IsEmpty()) { return(JError("data is empty")); } Schema.Domain.Entity entityMeta = null; if (model.EntityId.HasValue && !model.EntityId.Value.Equals(Guid.Empty)) { entityMeta = _entityFinder.FindById(model.EntityId.Value); } else if (model.EntityName.IsNotEmpty()) { entityMeta = _entityFinder.FindByName(model.EntityName); } if (entityMeta == null) { return(NotFound()); } var childAttributes = _attributeFinder.FindByEntityName(entityMeta.Name); if (model.Data.StartsWith("[")) { var details = new List <Entity>(); var items = JArray.Parse(model.Data.UrlDecode()); if (items.Count > 0) { foreach (var c in items) { dynamic root = JObject.Parse(c.ToString()); Entity detail = new Entity(entityMeta.Name); foreach (JProperty p in root) { var attr = childAttributes.Find(n => n.Name.IsCaseInsensitiveEqual(p.Name)); if (attr != null && p.Value != null) { detail.SetAttributeValue(p.Name.ToString().ToLower(), detail.WrapAttributeValue(_entityFinder, attr, p.Value.ToString())); } } details.Add(detail); } } return(_dataCreater.CreateMany(details).CreateResult(T)); } else { dynamic root = JObject.Parse(model.Data.UrlDecode()); Entity detail = new Entity(entityMeta.Name); foreach (JProperty p in root) { var attr = childAttributes.Find(n => n.Name.IsCaseInsensitiveEqual(p.Name)); if (attr != null) { detail.SetAttributeValue(p.Name.ToString().ToLower(), detail.WrapAttributeValue(_entityFinder, attr, p.Value.ToString())); } } var id = _dataCreater.Create(detail); return(CreateSuccess(new { id = id })); } }
public Guid Create(AggregateRoot aggregateRoot, Guid?systemFormId = null, bool ignorePermissions = false) { AggregateRootMetaData aggRootMetaData = GetAggregateRootMetaData(aggregateRoot, systemFormId); var thisId = Guid.Empty; try { _organizationDataProvider.BeginTransaction(); InternalOnCreate(aggregateRoot, OperationStage.PreOperation, aggRootMetaData); //关联Id thisId = Guid.NewGuid(); foreach (var c in aggregateRoot.ChildEntities) { string name = c.Name, relationshipname = c.Relationshipname, refname = string.Empty; if (relationshipname.IsNotEmpty()) { var relationShipMetas = _relationShipFinder.FindByName(c.Relationshipname); if (null != relationShipMetas && relationShipMetas.ReferencedEntityId == c.Entityid) { refname = relationShipMetas.ReferencingAttributeName; } if (refname.IsNotEmpty()) { c.Entity.SetAttributeValue(refname, new EntityReference(aggregateRoot.MainEntity.Name, thisId)); } } } var childEntities = aggregateRoot.ChildEntities.Select(x => x.Entity).ToList(); var entityNames = childEntities.Select(n => n.Name).Distinct().ToList(); foreach (var item in entityNames) { var items = childEntities.Where(n => n.Name.IsCaseInsensitiveEqual(item)).ToList(); var creatingRecords = items.Where(n => n.Name.IsCaseInsensitiveEqual(item) && n.GetIdValue().Equals(Guid.Empty)).ToList(); if (creatingRecords.NotEmpty()) { _dataCreater.CreateMany(creatingRecords); } } aggregateRoot.MainEntity.SetIdValue(thisId); _dataCreater.Create(aggregateRoot.MainEntity); InternalOnCreate(aggregateRoot, OperationStage.PostOperation, aggRootMetaData); _organizationDataProvider.CommitTransaction(); } catch (Exception e) { _organizationDataProvider.RollBackTransaction(); OnException(e); } return(thisId); }
public object Send(NotifyBody body) { var ibody = body as InternalNotifyBody; Entity entity = new Entity("notice"); entity.SetAttributeValue("name", ibody.Subject); entity.SetAttributeValue("content", ibody.Content); entity.SetAttributeValue("linkto", ibody.LinkTo); entity.SetAttributeValue("isread", false); entity.SetAttributeValue("typecode", new OptionSetValue(ibody.TypeCode)); entity.SetAttributeValue("ownerid", new OwnerObject(OwnerTypes.SystemUser, ibody.ToUserId)); _dataCreater.Create(entity, true); return(true); }
public IActionResult CreateOrganization(EditOrganizationModel model) { string msg = string.Empty; if (ModelState.IsValid) { Entity entity = new Entity("organization"); entity.SetIdValue(Guid.NewGuid()); entity.SetAttributeValue("Name", model.Name); entity.SetAttributeValue("LanguageId", (int)model.LanguageId); entity.SetAttributeValue("State", model.State); entity.SetAttributeValue("Description", model.Description); entity.SetAttributeValue("BaseCurrencyId", new EntityReference("currency", model.BaseCurrencyId)); entity.SetAttributeValue("ManagerId", model.ManagerId); var id = _dataCreater.Create(entity); return(JOk(T["created_success"], new { id = id })); } msg = GetModelErrors(ModelState); return(JOk(T["created_error"] + ": " + msg)); }
/// <summary> /// 创建记录 /// </summary> /// <param name="entityId"></param> /// <param name="objectId"></param> /// <param name="file"></param> /// <returns></returns> public virtual async Task <Entity> CreateAsync(Guid entityId, Guid objectId, IFormFile file) { if (file.Length > 0) { string dir = _webHelper.MapPath(Path, true); Guid id = Guid.NewGuid(); string fileName = id.ToString() + System.IO.Path.GetExtension(file.FileName); string savePath = dir + fileName; await file.SaveAs(savePath, _settingFinder, _webHelper).ConfigureAwait(false); Entity ent = new Entity(EntityName) .SetIdValue(id) .SetAttributeValue("name", file.FileName) .SetAttributeValue("filesize", file.Length) .SetAttributeValue("mimetype", file.ContentType) .SetAttributeValue("cdnpath", Path + fileName) .SetAttributeValue("entityid", entityId) .SetAttributeValue("objectid", objectId); _dataCreater.Create(ent); return(ent); } return(null); }
public IActionResult Post(SaveDataModel model) { if (model.EntityId.Equals(Guid.Empty)) { return(NotFound()); } var entityMetaData = _entityFinder.FindById(model.EntityId); if (entityMetaData == null) { return(NotFound()); } var attributeMetaDatas = _attributeFinder.FindByEntityId(model.EntityId); bool isNew = !(model.RecordId.HasValue && !model.RecordId.Value.Equals(Guid.Empty)); var thisId = Guid.Empty; try { Core.Data.Entity entity = new Core.Data.Entity(entityMetaData.Name); dynamic headData = JObject.Parse(model.Data); foreach (JProperty p in headData) { var attr = attributeMetaDatas.Find(n => n.Name.IsCaseInsensitiveEqual(p.Name)); if (attr != null && p.Value != null) { entity.SetAttributeValue(p.Name.ToString().ToLower(), entity.WrapAttributeValue(_entityFinder, attr, p.Value.ToString())); } } if (isNew) { if (model.RelationShipName.IsNotEmpty() && model.ReferencedRecordId.HasValue)//如果存在关联关系 { var relationShipMetas = _relationShipFinder.FindByName(model.RelationShipName); if (null != relationShipMetas && relationShipMetas.ReferencingEntityId == model.EntityId && entity.GetStringValue(relationShipMetas.ReferencingAttributeName).IsEmpty()) { //设置当前记录关联字段的值 entity.SetAttributeValue(relationShipMetas.ReferencingAttributeName, new EntityReference(relationShipMetas.ReferencedEntityName, model.ReferencedRecordId.Value)); } } if (!model.StageId.Equals(Guid.Empty))//业务流程的阶段 { entity.SetAttributeValue("StageId", model.StageId); } thisId = _dataCreater.Create(entity); if (!model.StageId.Equals(Guid.Empty))//业务流程的阶段 { _businessProcessFlowInstanceUpdater.UpdateForward(model.BusinessFlowId, model.BusinessFlowInstanceId, model.StageId, thisId); } } else { thisId = model.RecordId.Value; entity.SetIdValue(model.RecordId.Value); _dataUpdater.Update(entity); } //单据体 if (model.Child.IsNotEmpty()) { var childs = JArray.Parse(model.Child.UrlDecode()); if (childs.Count > 0) { List <Core.Data.Entity> childEntities = new List <Core.Data.Entity>(); List <string> entityNames = new List <string>(); foreach (var c in childs) { dynamic root = JObject.Parse(c.ToString()); string name = root.name, relationshipname = root.relationshipname, refname = string.Empty; if (!entityNames.Exists(n => n.IsCaseInsensitiveEqual(name))) { entityNames.Add(name); } var data = root.data; var childAttributes = _attributeFinder.FindByEntityName(name); if (relationshipname.IsNotEmpty()) { var relationShipMetas = _relationShipFinder.FindByName(relationshipname); if (null != relationShipMetas && relationShipMetas.ReferencedEntityId == model.EntityId) { refname = relationShipMetas.ReferencingAttributeName; } } Core.Data.Entity detail = new Core.Data.Entity(name); foreach (JProperty p in data) { var attr = childAttributes.Find(n => n.Name.IsCaseInsensitiveEqual(p.Name)); if (attr != null && p.Value != null) { detail.SetAttributeValue(p.Name.ToString().ToLower(), detail.WrapAttributeValue(_entityFinder, attr, p.Value.ToString())); } } //关联主记录ID if (refname.IsNotEmpty()) { detail.SetAttributeValue(refname, new EntityReference(entityMetaData.Name, thisId)); } childEntities.Add(detail); } //批量创建记录 if (childEntities.NotEmpty()) { foreach (var item in entityNames) { var items = childEntities.Where(n => n.Name.IsCaseInsensitiveEqual(item)).ToList(); var creatingRecords = items.Where(n => n.Name.IsCaseInsensitiveEqual(item) && n.GetIdValue().Equals(Guid.Empty)).ToList(); if (creatingRecords.NotEmpty()) { _dataCreater.CreateMany(creatingRecords); } if (!isNew) { foreach (var updItem in items.Where(n => n.Name.IsCaseInsensitiveEqual(item) && !n.GetIdValue().Equals(Guid.Empty))) { _dataUpdater.Update(updItem); } } } } } } } catch (Exception ex) { return(JError(ex.InnerException != null ? ex.InnerException.Message : ex.Message)); } if (isNew) { return(CreateSuccess(new { id = thisId })); } return(UpdateSuccess(new { id = thisId })); }
private bool ImportCore(ImportFile file, ImportMap map, List <dynamic> data, Action <int, object, string, int, Guid> itemProcceed) { var mappings = new List <ColumnMapping>().DeserializeFromJson(map.MapCustomizations); var columns = new List <string>().DeserializeFromJson(file.HeaderRow); var attributes = _attributeFinder.FindByEntityName(file.TargetEntityName); //更新记录时,根据哪些字段查询已存在的记录 var updatePrimaryFields = new List <string> { attributes.Find(x => x.IsPrimaryField).Name }; updatePrimaryFields.AddRange(mappings.Where(x => x.IsUpdatePrimaryField).Select(x => x.Mapping.Attribute)); int rowIndex = 0, failureCount = 0; foreach (var d in data) { rowIndex++; StringBuilder rowError = new StringBuilder(); var entity = new Entity(file.TargetEntityName); var retrieveFilter = new Dictionary <string, object>(); for (int i = 0; i < columns.Count; i++) { var value = d[i]; var mapping = mappings[i].Mapping; //字段 var attr = attributes.Find(x => x.Name.IsCaseInsensitiveEqual(mapping.Attribute)); //是否类型 if (attr.TypeIsBit() || attr.TypeIsState()) { if (value == null) { if (mapping.NullHandle == "ignore") { } else if (mapping.NullHandle == "defaultvalue") { value = attr.DefaultValue; } else if (mapping.NullHandle.IsInteger()) { var item = _stringMapFinder.Find(x => x.AttributeId == attr.AttributeId && x.Value == int.Parse(mapping.NullHandle)); if (item != null) { value = item.Value; } else { //失败记录 rowError.AppendLine($"\"{columns[i]}\"的值\"{value}\"不存在"); } } } else { var v = (string)value; var item = _stringMapFinder.Find(x => x.AttributeId == attr.AttributeId && x.Name == v); if (item != null) { value = item.Value; } else { //失败记录 rowError.AppendLine($"\"{columns[i]}\"的值\"{value}\"不存在"); } } } //选项集类型 else if (attr.TypeIsPickList() || attr.TypeIsStatus()) { if (value == null) { if (mapping.NullHandle == "ignore") { } else if (mapping.NullHandle == "defaultvalue") { value = attr.DefaultValue; } else if (((string)value).IsInteger()) { var item = attr.PickLists.Find(x => x.Value == (int)value); if (item != null) { value = new OptionSetValue(item.Value); } else { //失败记录 rowError.AppendLine($"\"{columns[i]}\"的值\"{value}\"不存在"); } } } else { var v = (string)value; var item = _optionSetDetailServiceFinder.Find(x => x.OptionSetId == attr.OptionSetId && x.Name == v); if (item != null) { value = new OptionSetValue(item.Value); } else { //失败记录 rowError.AppendLine($"\"{columns[i]}\"的值\"{value}\"不存在"); } } } //引用类型 else if (attr.TypeIsLookUp() || attr.TypeIsOwner() || attr.TypeIsCustomer()) { if (value != null) { var criteria = new Dictionary <string, object>(); if (((string)value).IsGuid()) { criteria.Add(entity.IdName, value); } if (mapping.LookupName.IsNotEmpty()) { criteria.Add(mapping.LookupName, value); } else { var primaryField = _attributeFinder.Find(x => x.EntityId == attr.ReferencedEntityId && x.IsPrimaryField == true); criteria.Add(primaryField.Name, value); } var filter = new Sdk.Abstractions.Query.FilterExpression(); foreach (var c in criteria) { filter.AddCondition(c.Key, Sdk.Abstractions.Query.ConditionOperator.Equal, c.Value); } var matchedCount = _aggregateService.Count(attr.ReferencedEntityName, filter); if (matchedCount > 1) { //失败记录 rowError.AppendLine($"\"{columns[i]}\"的值\"{value}\"不唯一"); } else { var referenced = _dataFinder.RetrieveByAttribute(attr.ReferencedEntityName, criteria, new List <string> { attr.ReferencedEntityName + "Id" }); if (referenced.NotEmpty()) { if (attr.TypeIsOwner()) { value = new OwnerObject(OwnerTypes.SystemUser, referenced.Id); } else { value = new EntityReference(attr.ReferencedEntityName, referenced.Id); } } else { //失败记录 rowError.AppendLine($"\"{columns[i]}\"的值\"{value}\"不存在"); } } } } //金额类型 else if (attr.TypeIsMoney() || attr.TypeIsSmallMoney()) { if (value != null) { if (decimal.TryParse((string)value, out decimal v)) { value = new Money(v); } else { //失败记录 rowError.AppendLine($"\"{columns[i]}\"的值\"{value}\"格式错误"); } } } //浮点型类型 else if (attr.TypeIsDecimal() || attr.TypeIsFloat()) { if (value != null) { if (!decimal.TryParse((string)value, out _)) { //失败记录 rowError.AppendLine($"\"{columns[i]}\"的值\"{value}\"格式错误"); } } } //整型类型 else if (attr.TypeIsInt()) { if (value != null) { if (!((string)value).IsInteger()) { //失败记录 rowError.AppendLine($"\"{columns[i]}\"的值\"{value}\"格式错误"); } } } //日期类型 else if (attr.TypeIsDateTime() || attr.TypeIsSmallDateTime()) { if (value != null) { if (!((string)value).IsDateTime()) { //失败记录 rowError.AppendLine($"\"{columns[i]}\"的值\"{value}\"格式错误"); } } } else if (value != null) { value = (string)value; } if (rowError.Length == 0 && value != null) { entity.SetAttributeValue(attr.Name, value); if (updatePrimaryFields.Exists(x => x.IsCaseInsensitiveEqual(attr.Name))) { retrieveFilter.Add(attr.Name, value); } } } int errorType = rowError.Length > 0 ? 2 : 0;//错误类型:数据=2 //重复数据的操作 if (retrieveFilter.Count > 0) { var existsEntity = _dataFinder.RetrieveByAttribute(file.TargetEntityName, retrieveFilter, updatePrimaryFields, true); //不导入重复数据 if (file.DuplicateDetection == 1 && existsEntity.NotEmpty()) { rowError.AppendLine("记录已存在"); } //覆盖导入 else if (file.DuplicateDetection == 2 && existsEntity.NotEmpty()) { entity.SetIdValue(existsEntity.Id); } //仅覆盖重复数据 else if (file.DuplicateDetection == 3) { if (existsEntity.NotEmpty()) { entity.SetIdValue(existsEntity.Id); } else { rowError.AppendLine("记录不存在"); } } } Guid recordId = entity.Id; //本行数据验证通过 if (rowError.Length == 0) { try { if (recordId.IsEmpty()) { recordId = _dataCreater.Create(entity); } else { _dataUpdater.Update(entity); } } catch (Exception e) { errorType = 1;//错误类型:系统 rowError.AppendLine(e.Message); } } if (rowError.Length > 0) { failureCount++; } //每行导入结果 itemProcceed(rowIndex, d, rowError.ToString(), errorType, recordId); } //文件导入结果 file.SuccessCount = data.Count - failureCount; file.FailureCount = failureCount; _importFileService.Update(file); return(true); }
private Guid CreateFromMap_Copy(EntityMap entityMap, Guid sourceRecordId) { var headTargetEntityMeta = _entityFinder.FindById(entityMap.TargetEntityId); var headTargetAttributes = _attributeFinder.FindByEntityId(entityMap.TargetEntityId); //引用源实体的字段 var headRelationShipMeta = _relationShipFinder.FindByName(entityMap.RelationShipName); var refAttr = headTargetAttributes.Find(n => n.AttributeId == headRelationShipMeta.ReferencingAttributeId); if (entityMap.MapType == MapType.CopyOne) { //查询是否已生成记录 QueryExpression query_target = new QueryExpression(headTargetEntityMeta.Name, _languageId); query_target.ColumnSet.AddColumn(headTargetAttributes.Find(n => n.TypeIsPrimaryKey()).Name); query_target.Criteria.AddCondition(refAttr.Name, ConditionOperator.Equal, sourceRecordId); var existsRecord = _dataFinder.Retrieve(query_target); if (existsRecord.NotEmpty()) { OnException(_loc["entitymap_copyone_error"]); return(Guid.Empty); } } Guid newId = Guid.Empty; //源记录 var sourceRecord = _dataFinder.RetrieveById(entityMap.SourceEnttiyName, sourceRecordId); if (sourceRecord.IsEmpty()) { OnException(_loc["notfound_record"]); return(Guid.Empty); } //单据头 var attributeMaps = _attributeMapFinder.Query(n => n.Where(f => f.EntityMapId == entityMap.EntityMapId)); if (attributeMaps.IsEmpty()) { OnException(_loc["entitymap_emptyheadattributemap"]); return(Guid.Empty); } //单据体 var childEntityMap = _entityMapFinder.FindByParentId(entityMap.EntityMapId); //单据头字段元数据 var headSourceAttributes = _attributeFinder.FindByEntityId(entityMap.SourceEntityId); //新增单据头信息 Entity headEntity = new Entity(entityMap.TargetEnttiyName); foreach (var attrMap in attributeMaps) { if (!headSourceAttributes.Exists(n => n.AttributeId == attrMap.SourceAttributeId) || !headTargetAttributes.Exists(n => n.AttributeId == attrMap.TargetAttributeId)) { continue; } var attr = headTargetAttributes.Find(n => n.AttributeId == attrMap.TargetAttributeId); if (attr == null) { continue; } var value = sourceRecord[attrMap.SourceAttributeName]; if (value == null && attrMap.DefaultValue.IsNotEmpty()) { value = attrMap.DefaultValue; } headEntity.SetAttributeValue(attr.Name, sourceRecord.WrapAttributeValue(_entityFinder, attr, value)); } //关联来源单据ID headEntity.SetAttributeValue(refAttr.Name, sourceRecord.WrapAttributeValue(_entityFinder, refAttr, sourceRecord.GetIdValue())); try { _organizationDataProvider.BeginTransaction(); InternalOnMap(sourceRecord, headEntity, OperationStage.PreOperation, headTargetEntityMeta, headTargetAttributes); newId = _dataCreater.Create(headEntity); //新增单据体信息 if (childEntityMap != null) { var childAttributeMaps = _attributeMapFinder.Query(n => n.Where(f => f.EntityMapId == childEntityMap.EntityMapId)); if (childAttributeMaps.NotEmpty()) { var childTargetEntityMeta = _entityFinder.FindById(childEntityMap.TargetEntityId); var childTargetAttributesMeta = _attributeFinder.FindByEntityId(childEntityMap.TargetEntityId); var childSourceAttributesMeta = _attributeFinder.FindByEntityId(childEntityMap.SourceEntityId); var childRelationShips = childEntityMap.RelationShipName.SplitSafe(","); //源单据体与源单据头的关系 var childSourceRelationShipMeta = _relationShipFinder.FindByName(childRelationShips[0]); //目标单据体与目标单据头的关系 var childTargetRelationShipMeta = _relationShipFinder.FindByName(childRelationShips[1]); //源单据体数据 QueryExpression query_source = new QueryExpression(childEntityMap.SourceEnttiyName, _languageId); query_source.ColumnSet.AllColumns = true; var refKey = headSourceAttributes.Find(n => n.AttributeId == childSourceRelationShipMeta.ReferencedAttributeId).Name; query_source.Criteria.AddCondition(refKey, ConditionOperator.Equal, sourceRecordId); var childSourceRecords = _dataFinder.RetrieveAll(query_source); if (childSourceRecords.NotEmpty()) { //引用单据头的字段 var headRefAttr = childTargetAttributesMeta.Find(n => n.AttributeId == childTargetRelationShipMeta.ReferencingAttributeId); //引用源单据体的字段 var refSourceAttr = childTargetAttributesMeta.Find(n => n.ReferencedEntityId.HasValue && n.ReferencedEntityId.Value == childEntityMap.SourceEntityId); foreach (var item in childSourceRecords) { //目标单据体 Entity childTargetRecord = new Entity(childEntityMap.TargetEnttiyName); foreach (var attrMap in childAttributeMaps) { if (!childSourceAttributesMeta.Exists(n => n.AttributeId == attrMap.SourceAttributeId) || !childTargetAttributesMeta.Exists(n => n.AttributeId == attrMap.TargetAttributeId)) { continue; } var attr = childTargetAttributesMeta.Find(n => n.AttributeId == attrMap.TargetAttributeId); if (attr == null) { continue; } var value = item[attrMap.SourceAttributeName]; if (value == null && attrMap.DefaultValue.IsNotEmpty()) { value = attrMap.DefaultValue; } childTargetRecord.SetAttributeValue(attrMap.TargetAttributeName, sourceRecord.WrapAttributeValue(_entityFinder, attr, value)); } //关联来源单据体记录ID if (refSourceAttr != null) { childTargetRecord.SetAttributeValue(refSourceAttr.Name, sourceRecord.WrapAttributeValue(_entityFinder, refSourceAttr, item.GetIdValue())); } //单据头ID childTargetRecord.SetAttributeValue(headRefAttr.Name, sourceRecord.WrapAttributeValue(_entityFinder, headRefAttr, newId)); _dataCreater.Create(childTargetRecord); } } } } _organizationDataProvider.CommitTransaction(); InternalOnMap(sourceRecord, headEntity, OperationStage.PostOperation, headTargetEntityMeta, headTargetAttributes); } catch (Exception e) { _organizationDataProvider.RollBackTransaction(); newId = Guid.Empty; OnException(e); } return(newId); }