void Main() {
var MyMonitor = new Devart.Data.Oracle.OracleMonitor();
MyMonitor.IsActive = true;
var faker = new RiaInvokeDataFaker(@"E:\软件\Linq20160126\LINQPad.xp510.com\LINQPad\修改备件采购订单.xml", "修改备件采购订单");
using (var transaction = new TransactionScope()) {
var order = faker.GetEntity<PartsPurchaseOrder>("partsPurchaseOrder");
order.RowVersion = this.PartsPurchaseOrders.Where(p => p.Id == order.Id).SetMergeOption(MergeOption.NoTracking).First().RowVersion;
new PartsPurchaseOrderAch(new DcsDomainService(this)).修改备件采购订单(order,
faker.GetList<PartsPurchaseOrderDetail>("partsPurchaseOrderDetails"),
faker.GetList<PurchasePlanDetail>("purchasePlanDetails").ToArray());
}
} partial class PartsPurchaseOrderAch : DcsSerivceAchieveBase {
public PartsPurchaseOrderAch(DcsDomainService domainService)
: base(domainService) {
} public void 修改备件采购订单(PartsPurchaseOrder partsPurchaseOrder, IEnumerable<PartsPurchaseOrderDetail> partsPurchaseOrderDetails, PurchasePlanDetail[] purchasePlanDetails) {
this.修改配件采购订单私有(partsPurchaseOrder, partsPurchaseOrderDetails.ToList(), purchasePlanDetails.ToList());
} internal void 修改配件采购订单私有(PartsPurchaseOrder partsPurchaseOrder, List<PartsPurchaseOrderDetail> partsPurchaseOrderDetails, List<PurchasePlanDetail> purchasePlanDetails) {
this.UpdateToDatabase(partsPurchaseOrder);
var groupedSparCount = partsPurchaseOrderDetails.GroupBy(p => p.SparePartId).Count(c => c.Count() > 1);
if(groupedSparCount > 0)
throw new ValidationException("存在重复备件");
//查询最小订货单元
var detailsPartIds = purchasePlanDetails.Where(p => !p.IsSourceDetail).Select(p => p.SparePartId).Distinct();
var minOrderUnitsQuery = this.ObjectContext.MinOrderUnits.Where(m => detailsPartIds.Contains(m.PartId) && m.OrderKind == (int)DcsMinOrderUnitOrderKind.采购).ToArray();
//查询要货计划主单
var purchasePlanIds = purchasePlanDetails.Select(p => p.ParentId).Distinct();
var purchasePlans = ObjectContext.PurchasePlans.Include("PurchasePlanDetails").Where(p => purchasePlanIds.Contains(p.Id)).ToArray();
var dbPurchasePlanDetails = purchasePlans.SelectMany(p => p.PurchasePlanDetails).ToArray();
//查询配件采购价格
var sparePartIds = purchasePlanDetails.Select(v => v.SparePartId).Distinct();
var swapSparePartIds = purchasePlanDetails.Select(v => v.SwapSparePartId).Distinct().ToArray();
var partsPurchasePricings = this.ObjectContext.PartsPurchasePricings.Where(p => (sparePartIds.Contains(p.PartId) || swapSparePartIds.Contains(p.PartId)) && p.Status != (int)DcsPartsPurchasePricingStatus.作废).ToArray();
//查询配件FOB价格
var date = DateTime.Now;
var partsFOBs = this.ObjectContext.PartsFOBs.Where(f => sparePartIds.Contains(f.PartId) && f.BeginTime < date && f.EndTime > date).ToArray();
var olePartsPurchaseOrderDetails = ObjectContext.PartsPurchaseOrderDetails.Where(p => p.PartsPurchaseOrderId == partsPurchaseOrder.Id).ToList();
//处理配件采购订单清单 foreach(var detail in from groupedPlanDetail in
(from purchasePlanDetail in purchasePlanDetails.Where(p => !p.IsSourceDetail)
group purchasePlanDetail by new {
purchasePlanDetail.SparePartId,
purchasePlanDetail.SparePartCode
}
into planDetails
select new {
SumTheFiling = planDetails.Sum(p => p.TheFilings ?? 0),
planDetails.Key.SparePartId,
SparepartCode = planDetails.Key.SparePartCode
})
join oldPurchaseOrderDetail in olePartsPurchaseOrderDetails on groupedPlanDetail.SparePartId equals oldPurchaseOrderDetail.SparePartId into oldpartsPurchaseOrderDetails
from oldpartsPurchaseOrderDetail in oldpartsPurchaseOrderDetails.DefaultIfEmpty()
select new {
groupedPlanDetail,
oldpartsPurchaseOrderDetail
}) {
if(detail.oldpartsPurchaseOrderDetail == null)
throw new ValidationException(string.Format("{0}要货计划清单对应的采购订单清单不存在", detail.groupedPlanDetail.SparepartCode));
detail.oldpartsPurchaseOrderDetail.OrderAmount = detail.groupedPlanDetail.SumTheFiling;
if(detail.oldpartsPurchaseOrderDetail.OrderAmount == 0)
DeleteFromDatabase(detail.oldpartsPurchaseOrderDetail);
//else
// UpdateToDatabase(detail.oldpartsPurchaseOrderDetail);
} foreach(var detail in from planDetail in purchasePlanDetails.Where(p => p.IsSourceDetail)
group planDetail by new {
planDetail.ParentId,
planDetail.SwapSparePartId,
planDetail.SwapSparePartCode,
planDetail.SwapSparePartName,
planDetail.Price,
planDetail.CurType,
planDetail.FOBPrice
}
into planDetails
join olePurchaseOrderDetail in olePartsPurchaseOrderDetails on planDetails.Key.SwapSparePartId equals olePurchaseOrderDetail.SparePartId into olePurchaseOrderDetails
from partsPurchaseOrderDetail in olePurchaseOrderDetails.DefaultIfEmpty()
join purchasePricing in partsPurchasePricings on planDetails.Key.SwapSparePartId equals purchasePricing.PartId into purchasePricings
from partsPurchasePricing in purchasePricings.DefaultIfEmpty()
join minOrderUnitQuery in minOrderUnitsQuery on planDetails.Key.SwapSparePartId equals minOrderUnitQuery.PartId into minOrderUnits
from minOrderUnit in minOrderUnits.DefaultIfEmpty()
join purchasePlan in purchasePlans on planDetails.Key.ParentId equals purchasePlan.Id
select new {
planDetails,
purchasePlan,
partsPurchaseOrderDetail,
partsPurchasePricing,
minOrderUnit
}) {
var purchasePlanDetail = detail.planDetails.First();
var sumTheFilings = detail.planDetails.Sum(p => p.TheFilings ?? 0);
if(detail.partsPurchaseOrderDetail != null) {
detail.partsPurchaseOrderDetail.OldOrderAmount += detail.partsPurchaseOrderDetail.OrderAmount;
detail.partsPurchaseOrderDetail.OrderAmount += sumTheFilings; UpdateToDatabase(detail.partsPurchaseOrderDetail);
} else {
if(detail.partsPurchasePricing == null)
throw new ValidationException("要货计划清单对应的配件采购价格不存在!");
var partsPurchaseOrderDetail = partsPurchaseOrderDetails.FirstOrDefault(p => p.SparePartId == purchasePlanDetail.SwapSparePartId); if(partsPurchaseOrderDetail == null) {
partsPurchaseOrderDetail = new PartsPurchaseOrderDetail() {
PartsPurchaseOrderId = partsPurchaseOrder.Id,
SparePartId = purchasePlanDetail.SwapSparePartId ?? 0,
SparePartCode = purchasePlanDetail.SwapSparePartCode,
SparePartName = purchasePlanDetail.SwapSparePartName,
UnitPrice = detail.partsPurchasePricing.PurchasePrice,
OrderAmount = sumTheFilings,
CurType = purchasePlanDetail.CurType,
FOBPrice = purchasePlanDetail.FOBPrice ?? 0,
pricepro = detail.partsPurchasePricing == null ? (int)DcsPartsPurchaseOrderDetailpricepro.暂估价 : detail.partsPurchasePricing.PriceType ?? 0,
MinQty = detail.minOrderUnit == null ? 0 : detail.minOrderUnit.MinQty,
SysQty = 0,
OldOrderAmount = 0,
ConfirmedAmount = 0,
};
partsPurchaseOrder.PartsPurchaseOrderDetails.Add(partsPurchaseOrderDetail);
partsPurchaseOrderDetails.Add(partsPurchaseOrderDetail);
var purchasePlansReverseList = new PartsPurOrderReverseList {
PartsPurchaseOrderDetail = partsPurchaseOrderDetail,
SpareId = partsPurchaseOrderDetail.SparePartId,
DataType = (int)DcsPurchasePlansReverseListDataType.新增,
Qty = 0
};
this.InsertToDatabase(purchasePlansReverseList);
} else {
partsPurchaseOrderDetail.OrderAmount += sumTheFilings;
} var purchasePlanAndOrderLink = new PurchasePlanAndOrderLink() {
PartsPurchaseOrder = partsPurchaseOrder,
PurchasePlanId = detail.purchasePlan.Id,
PurchasePlanDetail = purchasePlanDetail
};
partsPurchaseOrderDetail.PurchasePlanAndOrderLinks.Add(purchasePlanAndOrderLink);
this.InsertToDatabase(purchasePlanAndOrderLink);
}
} //更新要货计划清单 int nullValue = 0; //当int?类型值为null时的替代值,一般此值不会被实际应用。
var tempDetails = from planDetail in purchasePlanDetails
join dbSwapPlanDetail in dbPurchasePlanDetails on new {
planDetail.ParentId,
SparePartId = planDetail.SwapSparePartId ?? 0
} equals new {
dbSwapPlanDetail.ParentId,
dbSwapPlanDetail.SparePartId
} into planDetails
from dbSwapPlanDetail in planDetails.DefaultIfEmpty()
join dbPlanDetail in dbPurchasePlanDetails on new {
planDetail.ParentId,
planDetail.SparePartId
} equals new {
dbPlanDetail.ParentId,
dbPlanDetail.SparePartId
} into oldplanDetails
from dbPlanDetail in oldplanDetails.DefaultIfEmpty() join fob in partsFOBs on new {
SwapSparePartId = planDetail.SwapSparePartId ?? 0,
CurType = planDetail.CurType ?? 0
} equals new {
SwapSparePartId = fob.PartId,
CurType = fob.CurrencyKind
} into fobs
from fob in fobs.DefaultIfEmpty()
//join purchasePlan in purchasePlans on planDetail.ParentId equals purchasePlan.Id into purPlans
//from purchasePlan in purPlans.DefaultIfEmpty()
join minOrderUnit in minOrderUnitsQuery on planDetail.SparePartId equals minOrderUnit.PartId into minOrderUnits
from minOrderUnit in minOrderUnits.DefaultIfEmpty()
join purchasePricing in partsPurchasePricings on planDetail.SwapSparePartId equals purchasePricing.PartId into purchasePricings
from partsPurchasePricing in purchasePricings.DefaultIfEmpty()
select new {
planDetail,
dbSwapPlanDetail,
dbPlanDetail, minOrderUnit,
partsPurchasePricing,
partFOB = fob,
//purchasePlan
};
foreach(var detail in tempDetails) {
if(detail.planDetail.IsSourceDetail) {
var purchasePlan = purchasePlans.FirstOrDefault(p => p.Id == detail.planDetail.ParentId);
if(purchasePlan == null)
throw new ValidationException("要货计划清单对应的要货计划单不存在");
if(detail.dbSwapPlanDetail != null) {
detail.dbSwapPlanDetail.PlanQty += detail.planDetail.TheFilings ?? 0;
UpdateToDatabase(detail.dbSwapPlanDetail);
} else {
if(detail.partsPurchasePricing == null)
throw new ValidationException(string.Format("备件[{0}]合同价已失效!", detail.planDetail.SwapSparePartCode));
detail.planDetail.SparePartId = detail.planDetail.SwapSparePartId ?? 0;
detail.planDetail.SparePartCode = detail.planDetail.SwapSparePartCode;
detail.planDetail.SparePartName = detail.planDetail.SwapSparePartName;
detail.planDetail.MinQty = detail.minOrderUnit == null ? nullValue : detail.minOrderUnit.MinQty;
detail.planDetail.SysQty = 0;
detail.planDetail.Price = detail.partsPurchasePricing.PurchasePrice;
detail.planDetail.FOBPrice = detail.partFOB == null ? 0 : detail.partFOB.Price;
detail.planDetail.FirstQty = detail.planDetail.TheFilings ?? 0;
detail.planDetail.PlanQty = detail.planDetail.TheFilings ?? 0;
purchasePlan.PurchasePlanDetails.Add(detail.planDetail);
UpdateToDatabase(purchasePlan);
new PurchasePlanAch(this.DomainService).UpdatePurchasePlanValidate(detail.planDetail.PurchasePlan);
var purchasePlansReverseList = new PurchasePlansReverseList {
PurchasePlanDetail = detail.planDetail,
SpareId = detail.planDetail.SparePartId,
DataType = (int)DcsPurchasePlansReverseListDataType.新增,
Qty = 0
};
this.InsertToDatabase(purchasePlansReverseList);
}
} else {
if(!swapSparePartIds.Contains(detail.planDetail.SparePartId)) {
detail.dbPlanDetail.PlanQty = detail.planDetail.TheFilings ?? 0;
//UpdateToDatabase(detail.oldPartsPurchasePlanDetail);
}
}
if(detail.planDetail.TheFilings == 0 || !detail.planDetail.TheFilings.HasValue) {
DeleteFromDatabase(detail.dbPlanDetail);
}
} //更新要货计划主单
foreach(var purchasePlan in purchasePlans) {
purchasePlan.SumPrice = purchasePlan.PurchasePlanDetails.Sum(d => d.PlanQty * d.Price);
purchasePlan.FOBPrice = purchasePlan.PurchasePlanDetails.Sum(d => d.PlanQty * d.FOBPrice);
//this.UpdateToDatabase(purchasePlan);
new PurchasePlanAch(this.DomainService).UpdatePurchasePlanValidate(purchasePlan);
} //处理累计订货量
List<VirtualBillDetail> virtualBillDetails = purchasePlanDetails.Select(detail => new VirtualBillDetail() {
OppositeSideUnitId = partsPurchaseOrder.PartsSupplierId,
清单备件Id = detail.IsSourceDetail? detail.SwapSparePartId.Value:detail.SparePartId,
清单备件编号 =detail.IsSourceDetail? detail.SwapSparePartCode:detail.SparePartCode,
清单原数量 = detail.IsSourceDetail ? 0 : detail.PlanQty,
清单倒冲后数量 = detail.TheFilings ?? 0
}).ToList();
if(partsPurchaseOrder.Status == (int)DcsPartsPurchaseOrderStatus.已确认) { this.倒冲累计订货量(virtualBillDetails, partsPurchasePricings, true);
} this.倒冲累计订货量(virtualBillDetails, partsPurchasePricings); //更新采购订单主单
partsPurchaseOrder.TotalAmount = partsPurchaseOrder.PartsPurchaseOrderDetails.Sum(d => d.UnitPrice * (d.OrderAmount));
var count = partsPurchaseOrderDetails.Count;
var d0 = partsPurchaseOrderDetails.Count(d => d.ConfirmedAmount > 0);
partsPurchaseOrder.KindRate = d0 / count;
partsPurchaseOrder.QtyRate = partsPurchaseOrderDetails.Sum(d => d.ConfirmedAmount) / partsPurchaseOrderDetails.Sum(d => d.OrderAmount);
partsPurchaseOrder.SumTax = (double)partsPurchaseOrder.PartsPurchaseOrderDetails.Sum(p => ((p.OrderAmount) * p.UnitPrice) * (decimal)0.17);
partsPurchaseOrder.IsMinOrderUnit = true;
this.SetMofifyInfo(partsPurchaseOrder);
if(partsPurchaseOrder.Status == (int)DcsPartsPurchaseOrderStatus.审核不通过)
partsPurchaseOrder.Status = (int)DcsPartsPurchaseOrderStatus.新增;
// UpdateToDatabase(partsPurchaseOrder);
this.UpdatePartsPurchaseOrderValidate(partsPurchaseOrder);
this.ObjectContext.SaveChanges();
} internal void 倒冲累计订货量(List<VirtualBillDetail> virtualBillDetails, IEnumerable<PartsPurchasePricing> partsPurchasePricings = null, bool is更新累计检验量 = false) { if(virtualBillDetails == null || !virtualBillDetails.Any())
return;
/*
1、如果 配件合同价=空, 则 调用服务:查询配件采购价格,依据:(配件采购价格.配件Id, 配件采购价格.配件供应商Id) in ((传入单据清单.[清单配件Id字段名称],传入单据主单.[主单对方单位Id字段名称])数组) 且 状态=生效 且 生效时间<当前时间 且 失效时间>当前时间。
*/
var SID = virtualBillDetails.FirstOrDefault().OppositeSideUnitId;
if(partsPurchasePricings == null) { var partIdsQuery = from detail in virtualBillDetails
select new {
id = detail.清单备件Id
};
partsPurchasePricings = new PartsPurchasePricingAch(this.DomainService).依据备件名称与供应商ID查询配件采购价格(partIdsQuery.Select(s => s.id).ToArray(), SID).ToList();
}
/*
2、循环传入单据清单,
在配件合同价中定位,定位依据:配件合同价.配件Id=传入单据清单.[清单配件Id字段名称] 且 配件合同价.配件供应商Id=传入单据主单.[主单对方单位Id字段名称]
如果存在,
如果 配件合同价.备件累计已订货数量+传入单据清单.[清单倒冲后数量字段名称]-传入单据清单.[清单原数量字段名称]>配件合同价.备件最大订货数量,则提示错误:“备件[传入单据清单.[备件编号字段名称]]最大订货数量为[配件采购价格.备件最大订货数量],累计订货数量为[配件采购价格.备件累计已订货数量],本次新增数量为[传入单据清单.[清单倒冲后数量字段名称]-传入单据清单.[清单原数量字段名称]],已超过最大订货数量,请修改本次订货数量!”
赋值:配件采购价格.备件累计已订货数量=配件合同价.备件累计已订货数量+传入单据清单.[清单倒冲后数量字段名称]-传入单据清单.[清单原数量字段名称]
*/
var errorInfo = new StringBuilder();
foreach(var detail in from virtualBillDetail in virtualBillDetails
join purchasePricing in partsPurchasePricings on new {
PartId = virtualBillDetail.清单备件Id
} equals new {
purchasePricing.PartId
} into purchasePricings
from partsPurchasePricing in purchasePricings.DefaultIfEmpty()
select new {
virtualBillDetail,
partsPurchasePricing,
}) {
if(detail.partsPurchasePricing != null) {
if(!is更新累计检验量) {
if(detail.partsPurchasePricing.MaxOrderQty != 0 && (detail.partsPurchasePricing.UsedOrderQty + detail.virtualBillDetail.清单倒冲后数量 - detail.virtualBillDetail.清单原数量) > detail.partsPurchasePricing.MaxOrderQty) {
errorInfo.AppendLine(string.Format("备件[{0}]最大订货数量为[{1}],累计订货数量为[{2}],本次新增数量为([" + (detail.virtualBillDetail.清单倒冲后数量 - detail.virtualBillDetail.清单原数量) + "]),已超过最大订货数量,请修改本次订货数量!", detail.virtualBillDetail.清单备件编号, detail.partsPurchasePricing.MaxOrderQty, detail.partsPurchasePricing.UsedOrderQty, detail.virtualBillDetail.清单倒冲后数量, detail.virtualBillDetail.清单原数量));
continue;
}
if(detail.virtualBillDetail.清单备件编号 == "GP9A34200C")
throw new ValidationException((detail.partsPurchasePricing.UsedOrderQty ?? 0) + detail.virtualBillDetail.清单倒冲后数量 - detail.virtualBillDetail.清单原数量 + " 累计订货量 " + detail.partsPurchasePricing.UsedOrderQty + " 清单倒冲后数量 " + detail.virtualBillDetail.清单倒冲后数量 + " 清单原数量 " + detail.virtualBillDetail.清单原数量 + detail.virtualBillDetail.清单备件编号);
detail.partsPurchasePricing.UsedOrderQty = (detail.partsPurchasePricing.UsedOrderQty ?? 0) + detail.virtualBillDetail.清单倒冲后数量 - detail.virtualBillDetail.清单原数量;
} else {
detail.partsPurchasePricing.UsedVerifyQty = (detail.partsPurchasePricing.UsedVerifyQty ?? 0) + detail.virtualBillDetail.清单倒冲后数量 - detail.virtualBillDetail.清单原数量;
}
this.UpdateToDatabase(detail.partsPurchasePricing);
} else {
throw new ValidationException(string.Format("{0}不存在配件采购价格",detail.virtualBillDetail.清单备件编号));
}
if(errorInfo.Length > 0)
throw new ValidationException(errorInfo.ToString());
//3、调用服务:更新配件采购价格。 }
} internal void UpdatePartsPurchaseOrderValidate(PartsPurchaseOrder partsPurchaseOrder) {
if (!string.IsNullOrEmpty(partsPurchaseOrder.SuppOrderCode))
partsPurchaseOrder.SuppOrderCode = partsPurchaseOrder.SuppOrderCode.ToUpper();
var userInfo = Utils.GetCurrentUserInfo();
partsPurchaseOrder.ModifierId = userInfo.Id;
partsPurchaseOrder.ModifierName = userInfo.Name;
partsPurchaseOrder.ModifyTime = DateTime.Now;
}
} partial class PurchasePlanAch : DcsSerivceAchieveBase {
public PurchasePlanAch(DcsDomainService service) : base(service) {
} internal void UpdatePurchasePlanValidate(PurchasePlan purchasePlan) {
var userInfo = Utils.GetCurrentUserInfo();
purchasePlan.ModifierId = userInfo.Id;
purchasePlan.ModifierName = userInfo.Name;
purchasePlan.ModifyTime = DateTime.Now;
}
} partial class PartsPurchasePricingAch : DcsSerivceAchieveBase {
public PartsPurchasePricingAch(DcsDomainService service) : base(service) {
} public IQueryable<PartsPurchasePricing> 依据备件名称与供应商ID查询配件采购价格(int[] sparePartIds, int supplierId) {
return this.ObjectContext.PartsPurchasePricings.Where(p => sparePartIds.Contains(p.PartId) && p.PartsSupplierId == supplierId && p.Status == (int)DcsPartsPurchasePricingStatus.生效);
}
} partial class DcsDomainService : System.ServiceModel.DomainServices.EntityFramework.LinqToEntitiesDomainService<DcsEntities> {
protected override DcsEntities CreateObjectContext() {
// return new DcsEntities(new EntityConnection());
return entities;
} private DcsEntities entities; public DcsDomainService(DcsEntities dcsEntities) : base() {
entities = dcsEntities;
} internal void InsertToDatabase(EntityObject entity) {
if (entity.EntityState != System.Data.EntityState.Detached)
ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Added);
else {
switch (entity.GetType().Name) {
case "ABCStrategy":
ObjectContext.ABCStrategies.AddObject((ABCStrategy)entity);
break;
default:
throw new NotImplementedException(string.Format(notImplementMsg, entity.GetType().Name, "add"));
}
}
} private void UpdateToDatabase<T>(ObjectSet<T> objectSet, T entity) where T : class {
if (ChangeSet == null || !ChangeSet.ChangeSetEntries.Any(e => ReferenceEquals(e.Entity, entity))) {
objectSet.AttachAsModified(entity);
return;
}
var original = ChangeSet.GetOriginal(entity);
if (original == null)
objectSet.AttachAsModified(entity);
else
objectSet.AttachAsModified(entity, original);
} private readonly string notImplementMsg = "上面没有实现{0}的{1}方法,自己实现一下吧"; internal void UpdateToDatabase(EntityObject entity) {
var entityName = entity.GetType().Name;
switch (entityName) {
case "ABCStrategy":
UpdateToDatabase(ObjectContext.ABCStrategies, (ABCStrategy)entity);
break;
// case "PartsPurchaseOrderDetail":
// UpdateToDatabase(ObjectContext.PartsPurchaseOrderDetails, (PartsPurchaseOrderDetail)entity);
// break;
// case "PurchasePlanDetail":
// UpdateToDatabase(ObjectContext.PurchasePlanDetails, (PurchasePlanDetail)entity);
// break;
case "PartsPurchaseOrder":
UpdateToDatabase(ObjectContext.PartsPurchaseOrders, (PartsPurchaseOrder)entity);
break;
default:
throw new NotImplementedException(string.Format(notImplementMsg, entityName, "update"));
}
} private void DeleteFromDatabase<T>(ObjectSet<T> objectSet, T entity) where T : class {
objectSet.Attach(entity);
objectSet.DeleteObject(entity);
} internal void DeleteFromDatabase(EntityObject entity) {
if (entity.EntityState == System.Data.EntityState.Added)
ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Detached);
else if (entity.EntityState != System.Data.EntityState.Detached)
ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Deleted);
else {
// ObjectContext.DeleteObject(entity);
switch (entity.GetType().Name) {
case "ABCStrategy":
DeleteFromDatabase(ObjectContext.ABCStrategies, (ABCStrategy)entity);
break;
default:
throw new NotImplementedException(string.Format(notImplementMsg, entity.GetType().Name, "delete"));
}
}
} internal DcsEntities GetObjectContext() {
return this.ObjectContext;
} internal ChangeSet GetChangeSet() {
return this.ChangeSet;
}
} class DcsSerivceAchieveBase {
protected readonly DcsEntities ObjectContext;
protected IQueryable ParamQueryable = null;
protected Utils.UserInfo UserInfo; protected DcsSerivceAchieveBase(DcsDomainService service) {
DomainService = service;
ChangeSet = service.GetChangeSet();
ObjectContext = service.GetObjectContext();
UserInfo = Utils.GetCurrentUserInfo();
// this.ParamQueryable = service.ParamQueryable;
} public IEnumerable<KeyValueItem> GetKeyValueItems(string category, string name, bool? isBuiltIn) {
if (category == null)
throw new ArgumentNullException("category");
if (name == null)
throw new ArgumentNullException("name"); var result = this.ObjectContext.KeyValueItems.Where(kv => kv.Status != (int)DcsBaseDataStatus.作废 && kv.Category == category && kv.Name == name);
if (isBuiltIn != null)
result = result.Where(kv => kv.IsBuiltIn == isBuiltIn.Value);
return result;
} protected void CheckEntityState(EntityObject entity) {
if (ChangeSet.GetChangeOperation(entity) == ChangeOperation.Update && entity.EntityState == System.Data.EntityState.Added) {
ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Unchanged);
}
} protected DcsDomainService DomainService; protected ChangeSet ChangeSet; protected void InsertToDatabase(EntityObject entity) {
DomainService.InsertToDatabase(entity);
}
public string GetErrorFilePath(string fileName) {
return Path.Combine(Path.GetDirectoryName(fileName) ?? "", string.Format("{0}_ErrorData{1}", Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName)));
} public string GetExportFilePath(string fileName) {
var enterpriseCode = Utils.GetCurrentUserInfo().EnterpriseCode;
return Path.Combine(GlobalVar.DOWNLOAD_EXPORTFILE_DIR, enterpriseCode, string.Format("{0}_{1:yyMMdd_HHmmss_fff}{2}", Path.GetFileNameWithoutExtension(fileName), DateTime.Now, Path.GetExtension(fileName)));
} public string GetImportFilePath(string fileName) {
return fileName;
}
protected void UpdateToDatabase(EntityObject entity) {
DomainService.UpdateToDatabase(entity);
} protected void DeleteFromDatabase(EntityObject entity) {
DomainService.DeleteFromDatabase(entity);
} /// <summary>
/// 赋与实体更新时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
protected void SetMofifyInfo<T>(T entity) where T : EntityObject {
SetMofifyInfo(entity, UserInfo);
} /// <summary>
/// 赋与实体更新时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
/// <param name="userInfo">用户信息</param>
protected void SetMofifyInfo<T>(T entity, Utils.UserInfo userInfo) where T : EntityObject {
foreach (var pro in entity.GetType().GetProperties()) {
switch (pro.Name.ToLower()) {
case "modifierid":
pro.SetValue(entity, userInfo.Id, null);
break;
case "modifiername":
pro.SetValue(entity, userInfo.Name, null);
break;
case "modifytime":
pro.SetValue(entity, DateTime.Now, null);
break;
}
}
} /// <summary>
/// 赋与实体创建时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
protected void SetCreateInfo<T>(T entity) where T : EntityObject {
SetCreateInfo(entity, UserInfo);
} /// <summary>
/// 捕捉自定义Oracle报错,启用分布式事务后,在RAC类型的Oracle数据上抛自定义错误,错误内容无法抛出,所以暂时用此方法来捕获错误
/// </summary>
/// <param name="ex"></param>
protected void ThrowOracleException(Exception ex) {
//System.Data.EntityCommandExecutionException: 执行命令定义时出错。有关详细信息,请参阅内部异常。 ---> Devart.Data.Oracle.OracleException: ORA-20001: 该经销商账户可用余额不足!
var strSource = ex.ToString();
if (Regex.Match(strSource, @"ORA-20\d{3}").Success)
throw new ValidationException(ObjectContext.ExecuteStoreQuery<string>("select 'ORA' || errorId || ': ' || errormsg from tmp_error").FirstOrDefault());
throw new Exception(strSource);
} /// <summary>
/// 赋与实体创建时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
/// <param name="userInfo">用户信息</param>
protected void SetCreateInfo<T>(T entity, Utils.UserInfo userInfo) where T : EntityObject {
foreach (var pro in entity.GetType().GetProperties()) {
switch (pro.Name.ToLower()) {
case "creatorid":
pro.SetValue(entity, userInfo.Id, null);
break;
case "creatorname":
pro.SetValue(entity, userInfo.Name, null);
break;
case "createtime":
pro.SetValue(entity, DateTime.Now, null);
break;
}
}
} /// <summary>
/// 赋与实体作废时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
protected void SetAbandonInfo<T>(T entity) where T : EntityObject {
SetAbandonInfo(entity, UserInfo);
} /// <summary>
/// 赋与实体作废时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
/// <param name="userInfo">用户信息</param>
protected void SetAbandonInfo<T>(T entity, Utils.UserInfo userInfo) where T : EntityObject {
foreach (var pro in entity.GetType().GetProperties()) {
switch (pro.Name.ToLower()) {
case "abandonerid":
pro.SetValue(entity, userInfo.Id, null);
break;
case "abandonername":
pro.SetValue(entity, userInfo.Name, null);
break;
case "abandontime":
pro.SetValue(entity, DateTime.Now, null);
break;
}
}
} protected void SetApproveInfo<T>(T entity) where T : EntityObject {
SetApproveInfo(entity, UserInfo);
} /// <summary>
/// 赋与实体审批时必要的信息
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="entity">实体</param>
/// <param name="userInfo">用户信息</param>
protected void SetApproveInfo<T>(T entity, Utils.UserInfo userInfo) where T : EntityObject {
foreach (var pro in entity.GetType().GetProperties()) {
switch (pro.Name.ToLower()) {
case "approverid":
pro.SetValue(entity, userInfo.Id, null);
break;
case "approvername":
pro.SetValue(entity, userInfo.Name, null);
break;
case "approvetime":
pro.SetValue(entity, DateTime.Now, null);
break;
}
}
} /// <summary>
/// 撤销所有服务端的修改
/// </summary>
protected void RejectChanges() {
var add = ObjectContext.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added);
foreach (var a in add)
ObjectContext.Detach(a.Entity); var modify = ObjectContext.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified);
foreach (var m in modify)
for (int i = 0; i < m.OriginalValues.FieldCount; i++)
m.CurrentValues.SetValue(i, m.OriginalValues[i]); var delete = ObjectContext.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted);
foreach (var d in delete) {
var entity = d.Entity;
var entitySetName = d.EntitySet.Name;
ObjectContext.Detach(entity);
ObjectContext.AttachTo(entitySetName, entity);
}
ObjectContext.AcceptAllChanges();
}
} class RiaInvokeDataFaker {
//@"C:\Users\Anders\Documents\LINQPad Queries\数据\修改备件采购订单.xml","修改备件采购订单"
public RiaInvokeDataFaker(string filePath, string opreation) {
// string context;
// using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) {
// TextReader tr = new StreamReader(fs, Encoding.UTF8);
// context = tr.ReadToEnd();
// context = context.Replace("xmlns=\"http://tempuri.org/\"", "");
// context = context.Replace("xmlns:a=\"http://schemas.datacontract.org/2004/07/Sunlight.Silverlight.Dcs.Web\"", "");
// context = context.Replace("<a:", "<");
// context = context.Replace("</a:", "</");
// }
xDoc = XDocument.Load(filePath);
xOpreation = xDoc.Element(xt + opreation);
} XNamespace xt = "http://tempuri.org/";
XNamespace xdcs = "http://schemas.datacontract.org/2004/07/" + typeof(UserQuery).BaseType.Namespace;
XNamespace xa = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"; public T GetEntity<T>(string paramName) {
var xElementName = (typeof(T).IsSubclassOf(typeof(EntityObject)) ? xdcs : xa) + GetTypeName<T>();
return Deserialization<T>(paramName, xElementName);
} public Dictionary<TKey, TValue> GetDictionary<TKey, TValue>(string paramName) {
return Deserialization<Dictionary<TKey, TValue>>(paramName, xa + "ArrayOfKeyValueOf" + GetTypeName<TKey>() + GetTypeName<TValue>());
} private string GetTypeName<T>() {
var type = typeof(T);
return type == typeof(Int32) ? "int" : typeof(T).IsSubclassOf(typeof(EntityObject)) ? type.Name : type.Name.Substring(0, 1).ToLower() + type.Name.Substring(1);
} public List<T> GetList<T>(string paramName) {
return Deserialization<List<T>>(paramName, (typeof(T).IsSubclassOf(typeof(EntityObject)) ? xdcs : xa) + "ArrayOf" + GetTypeName<T>());
} private XDocument xDoc; private XElement xOpreation; T Deserialization<T>(string paramName, XName xElementName) {
using (var stream = new MemoryStream()) {
var xElement = xOpreation.Element(xt + paramName);
if (xElement == null)
throw new NullReferenceException("xml源中没有" + paramName);
xElement.Name = xElementName;
xElement.Save(stream);
stream.Position = 0;
return Deserialization<T>(stream);
}
} T Deserialization<T>(Stream stream) {
var serialzier = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
return (T)serialzier.ReadObject(stream);
}
}