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

Linq 调试的更多相关文章

  1. Linqpad使用(调试Linq、结合linq调试业务场景、表格内编辑数据)

      linqpad是一款linq语句调试工具,功能如下: 1.直接执行linq语句并查看生成的原生sql语句 2.可结合linq+C#代码进行业务场景调试 3.表格内直接新增.修改.删除数据 4.直接 ...

  2. Linq调试实时输出信息扩展方法(摘抄)

    原文在此 [译]如何在C#中调试LINQ查询 原linq语句: var res = employees .Where(e => e.Gender == "Male") .Ta ...

  3. 如何在C#中调试LINQ查询

    原文:How to Debug LINQ queries in C# 作者:Michael Shpilt 译文:如何在C#中调试LINQ查询 译者:Lamond Lu 在C#中我最喜欢的特性就是LIN ...

  4. 10个用于C#.NET开发的基本调试工具

    在调试软件时,工具非常重要.获取正确的工具,然后再调试时提起正确的信息.根据获取的正确的错误信息,可以找到问题的根源所在.找到问题根源所在,你就能够解决该错误了. 你将看到我认为最基本的解决在C# . ...

  5. 调试Linq的时候获得相对应的SQL

    (query as System.Data.Objects.ObjectQuery).ToTraceString()

  6. 怎么调试lua性能

    怎么调试lua性能 我们的游戏使用的是Cocos2dx-lua 3.9的项目,最近发现我们的游戏.运行比较缓慢.想做一次性能优化了.其实主要分为GPU.CPU的分别优化.GPU部分的优化.网上有很多优 ...

  7. 微软发布TX(LINQ To Logs And Traces)

    微软开源技术公司于发布了Tx,这是一个Apache 2协议的开源项目,可以使用日志/跟踪文件辅助调试,以及创建实时监控和告警系统. 下面是几个引人关注的功能-- 允许在原始事件源上使用LINQ 允许在 ...

  8. .NET面试题系列[13] - LINQ to Object

    .NET面试题系列目录 名言警句 "C# 3.0所有特性的提出都是更好地为LINQ服务的" - Learning Hard LINQ是Language Integrated Que ...

  9. Code First开发系列之管理数据库创建,填充种子数据以及LINQ操作详解

    返回<8天掌握EF的Code First开发>总目录 本篇目录 管理数据库创建 管理数据库连接 管理数据库初始化 填充种子数据 LINQ to Entities详解 什么是LINQ to ...

随机推荐

  1. windows 版Tomcat 7.0的配置

    http://hi.baidu.com/liguohei/item/d6ea23ff904f98753d198b24 测试成功,截图 ~~~~~~~~~~~~~~~ 一.安装JDK 1.7 1.添加环 ...

  2. Ajaxupload插件超级简单使用(php的ci框架)

                         Ajaxupload简单使用  友情提示:1.蓝色文字为必修改内容.2.#字符后面是解释该代码段的主要内容  备注: 该实例是用php的ci框架直接接收图片并 ...

  3. MVVM in Depth

    这篇文章开始粗略的介绍了软件开发中松耦合的概念并讲述了使用MVC.MVP和MVVM三种模式达到松耦合.然后分析了这三种模式适用范围,其中: MVC(Model-View-Controller)适用于w ...

  4. nginx -- nginx平台初探(100%)

    初探nginx架构(100%) 众所周知,nginx性能高,而nginx的高性能与其架构是分不开的.那么nginx究竟是怎么样的呢?这一节我们先来初识一下nginx框架吧. nginx在启动后,在un ...

  5. 【原】hive 操作笔记

    1.建表: hive> CREATE TABLE pokes (foo INT, bar STRING); hive> CREATE TABLE invites (foo INT, bar ...

  6. nyoj 95 众数问题【水】

    众数问题 时间限制:3000 ms  |  内存限制:65535 KB 难度:3   描述 所谓众数,就是对于给定的含有N个元素的多重集合,每个元素在S中出现次数最多的成为该元素的重数, 多重集合S重 ...

  7. 与IO相关的等待事件troubleshooting-系列5

    'db file scattered read'         这是另一种常见的等待事件.他产生于Oracle从磁盘读取多个块到Buffer Cache中非连续(" scattered&q ...

  8. python实现应用程序在右键菜单中添加打开方式

    最近项目组开发的一个小工具想要在右键菜单中添加打开方式,以有道云笔记为例进行了需求拆解和代码编写 1.需求拆解: 如何实现手动添加右键菜单的打开方式: Step1:打开注册表编辑器,Win+R-> ...

  9. mysql中group_concat函数用法

    该函数返回带有来自一个组的连接的非NULL值的字符串结果.该函数是一个增强的Sybase SQL Anywhere支持的基本LIST()函数. 语法结构: GROUP_CONCAT([DISTINCT ...

  10. C#将数据以XML格式写入Excel

    本文转载:http://www.cnblogs.com/eflylab/archive/2008/09/21/1295580.html c#将数据导入Excel另类方法 今天公司突然给个Excel模版 ...